1

I have an ASP.NET MVC 5 Application where I have already implemented Signalr using ASP.NET SignalR V2. But now I need to integrate the Azure SignalR Service as well using the Server less method.

I searched lot of documentation, but I cannot find a correct way of calling the Hub method or connecting to Azure signalr Service. Please find the code what I tried so far

private static async void PushNotification(NotificationRequest notificationRequest, NotificationResponse notificationResponse, string signalRUrl, string authenticationType, Cookie cookie, ICredentials credentials, string accessToken, string userId, string cacheString)
    {
        if (authenticationType == "AzureSignalR")
        {
            HubConnection _connection = new HubConnectionBuilder().WithUrl(signalRUrl).Build();
        }
        else
        {
            using (var hubConnection = new HubConnection(signalRUrl))
            {
                IHubProxy notificationHubProxy = hubConnection.CreateHubProxy("NotificationHub");
                if (authenticationType != "AzureSignalR")
                {
                    ConfigureHubConnection(hubConnection, authenticationType, cookie, credentials);
                }

                try
                {
                    await hubConnection.Start();
                    await notificationHubProxy.Invoke("Send", notificationRequest, notificationResponse);
                    hubConnection.Stop();
                }
                catch (Exception e)
                {
                    if (hubConnection != null && !string.IsNullOrEmpty(hubConnection.ConnectionId))
                    {
                        hubConnection.Stop();
                    }
                }
            }
        }
        
    }

Here I am getting error on HubConnectionBuilder.WithUrl(), showing as WithURL() doesnot exists in library. I referenced the Microsoft.AspNetCore.SignalR.Client.

And this is my hub class derived inside Azure Function app.

public class NotificationHub : ServerlessHub
{
    [FunctionName("index")]
    public static IActionResult GetHomePage([HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req, ExecutionContext context)
    {
        var path = Path.Combine(context.FunctionAppDirectory, "content", "index.html");
        return new ContentResult
        {
            Content = File.ReadAllText(path),
            ContentType = "text/html",
        };
    }

    //[FunctionName("negotiate")]
    //public SignalRConnectionInfo Negotiate([HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req)
    //{
    //    return Negotiate(req.Headers["x-ms-signalr-user-id"]);
    //}

    [FunctionName("negotiate")]
    public static SignalRConnectionInfo Negotiate(
       [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
       [SignalRConnectionInfo(HubName = "NotificationHub")] SignalRConnectionInfo connectionInfo)
    {
        return connectionInfo;
    }
    [Authorize]
    [FunctionName(nameof(Send))]
    public async Task Send([SignalRTrigger] InvocationContext invocationContext, NotificationRequest notificationRequest, NotificationResponse notificationResponse)
    {
        try
        {
            await Clients.Clients(notificationResponse.ConnectionIds).SendAsync("SendNotification", notificationRequest);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    [FunctionName(nameof(OnDisconnected))]
    public async Task OnDisconnected([SignalRTrigger] InvocationContext invocationContext, ILogger logger)
    {
        var response = await APIService.CallDisconnectedTrigger(invocationContext.ConnectionId);
        if (response != null && response.ErrorMessages.Any())
        {
            string errorMessages = string.Join(", ", response.ErrorMessages);
            logger.LogInformation("Some error occured while disconnecting SignalR Connection. " + errorMessages);
        }
    }

}

Can someone please provide the code for connecting with Azure SignalR service from ASP.NET MVC Application?

Mohd Anzal
  • 157
  • 8

1 Answers1

0

I have Installed the Microsoft.AspNetCore.SignalR.Client.Core NuGet Package.

I have tried to add your code, Initially Even I got the same error.

enter image description here

I referenced the Microsoft.AspNetCore.SignalR.Client.

Even I have added the reference.

To get WithUrl, we need to Install the Microsoft.AspNetCore.SignalR.Client NuGet Package separately.

enter image description here

Now Iam able to add the WithUrl.

enter image description here

My .csproj file:

 <ItemGroup>
   <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="7.0.10" />
   <PackageReference Include="Microsoft.AspNetCore.SignalR.Client.Core" Version="7.0.10" />
 </ItemGroup>

The code which you have configured seems to be correct.

Found this Blog which has examples for ASP.NET and MVC.

Refer this Azure SignalR Messaging With .Net Core Console App which explains the Azure Signal R configuration in ASP.Net Core and same can be implemented in MVC Application based on your requirement.

Harshitha
  • 3,784
  • 2
  • 4
  • 9