从 ASP.NET MVC 应用程序调用 Azure SignalR 服务中心方法(无服务器方法)

问题描述 投票:0回答:1

我有一个 ASP.NET MVC 5 应用程序,我已经使用 ASP.NET SignalR V2 实现了 Signalr。但现在我还需要使用无服务器方法集成 Azure SignalR 服务。

我搜索了很多文档,但找不到调用 Hub 方法或连接到 Azure signalr 服务的正确方法。请找到我到目前为止尝试过的代码

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();
                    }
                }
            }
        }
        
    }

这里我在 HubConnectionBuilder.WithUrl() 上遇到错误,显示为库中不存在 WithURL() 。我引用了 Microsoft.AspNetCore.SignalR.Client。

这是我在 Azure Function 应用程序中派生的集线器类。

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);
        }
    }

}

有人可以提供从 ASP.NET MVC 应用程序连接 Azure SignalR 服务的代码吗?

asp.net-mvc azure-functions signalr azure-signalr
1个回答
0
投票

我已经安装了

Microsoft.AspNetCore.SignalR.Client.Core
NuGet 软件包。

我尝试添加你的代码,最初即使我遇到了同样的错误。

enter image description here

我引用了 Microsoft.AspNetCore.SignalR.Client。

即使我已经添加了参考。

要获取

WithUrl
,我们需要单独安装
Microsoft.AspNetCore.SignalR.Client
NuGet 包。

enter image description here

现在我可以添加

WithUrl

enter image description here

我的

.csproj
文件:

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

您配置的代码似乎是正确的。

找到这个博客,其中包含 ASP.NETMVC 的示例。

请参阅此Azure SignalR Messaging With .Net Core Console App,其中解释了

ASP.Net Core
中的Azure Signal R配置,并且可以根据您的要求在MVC应用程序中实现相同的配置。

© www.soinside.com 2019 - 2024. All rights reserved.