繁体   English   中英

从 .Net Framework Web 应用程序、控制台应用程序连接到 Azure SignalR Hub

[英]Connecting to Azure SignalR Hub from .Net Framework Web App, Console App

我有一个当前使用 ASP.Net SignalR 的 .Net Framework Web 应用程序 (v 4.6.1)。 我正在尝试添加另一个 SignalR 集线器,但允许此集线器使用Azure SignalR 服务进行连接,以便我们可以使用 REST API 向最终用户发送单向消息。

我一直在关注这些示例herehere来实现该功能。

有3个基本部分

  • 连接到集线器(工作)
  • 通过 REST API 发送消息(工作成功)
  • 作为最终用户接收消息(工作)

Hub和Azure SignalR Service已经创建完成,简单,无需展示。

代码示例

.Net Framework Web App Startup.cs 中的集线器连接

app.MapAzureSignalR(GetType().FullName, new HubConfiguration { EnableDetailedErrors = true },
    options =>
    {
        options.ConnectionString =
                    ConfigurationManager.ConnectionStrings["AzureSignalR"].ConnectionString;
    });

MapAzureSignalR来自这个 nuget 包

我还有客户端 JavaScript 来处理集线器连接和事件,这已经使用标准 ASP.Net SignalR 启动并运行了几个月。

客户端连接记录以下信息:

Error: You are using a version of the client that isn't compatible with the server. Client version 1.5, server version 2.0.
at Object.error (jquery.signalR.js:179)
at Object.success (jquery.signalR.js:728)
at i (scripts.bundle.js:2)
at Object.fireWith [as resolveWith] (scripts.bundle.js:2)
at A (scripts.bundle.js:4)
at XMLHttpRequest.<anonymous> (scripts.bundle.js:4)
at XMLHttpRequest.wrapFn (zone.js:1166)
at ZoneDelegate.invokeTask (zone.js:421)
at Zone.runTask (zone.js:188)
at ZoneTask.invokeTask [as invoke] (zone.js:496)

Web App 有以下包:

  <package id="Microsoft.AspNet.SignalR" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.SignalR.Core" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.SignalR.JS" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.SignalR.SqlServer" version="2.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.SystemWeb" version="2.4.0" targetFramework="net461" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNetCore.Authentication.Abstractions" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Authorization" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Authorization.Policy" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Connections.Abstractions" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Hosting.Abstractions" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Hosting.Server.Abstractions" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Http" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Http.Abstractions" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Http.Connections" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Http.Connections.Client" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Http.Connections.Common" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Http.Extensions" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Http.Features" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Routing" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.Routing.Abstractions" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.SignalR" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.SignalR.Common" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.SignalR.Core" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.SignalR.Protocols.Json" version="1.0.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.WebSockets" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.AspNetCore.WebUtilities" version="2.1.0" targetFramework="net461" />
  <package id="Microsoft.Azure.SignalR" version="1.0.6" targetFramework="net461" />
  <package id="Microsoft.Azure.SignalR.AspNet" version="1.0.0-preview1-10317" targetFramework="net461" />
  <package id="Microsoft.Azure.SignalR.Protocols" version="1.0.6" targetFramework="net461" />

.Net Framework 控制台应用程序中的集线器连接

var serviceUtils = new ServiceUtils(ConfigurationManager.ConnectionStrings["Azure:SignalR:ConnectionString"].ConnectionString);

var url = GetClientUrl(serviceUtils.Endpoint);

_connection = new HubConnection(url)
{
    ConnectionToken = serviceUtils.GenerateAccessToken(url, userId)
};

IHubProxy proxy = _connection.CreateHubProxy(hubName);

proxy.On("broadcastMessage", (string server, string message) =>
{
    Console.WriteLine($"[{DateTime.Now.ToString()}] Received message from server {server}: {message}");
});


_connection.Start();

在记录连接状态时,它会显示Disconnected, Connecting, Disconnected

.Net 核心代码示例

var serviceUtils = new ServiceUtils(connectionString);

var url = GetClientUrl(serviceUtils.Endpoint);

_connection = new HubConnectionBuilder()
    .WithUrl(url, options =>
    {
        options.AccessTokenProvider = () =>
            {
                return Task.FromResult(serviceUtils.GenerateAccessToken(url, userId));
            };
    }).Build();

_connection.On("broadcastMessage", (string server, string message) =>
{
    Console.WriteLine($"[{DateTime.Now.ToString()}] Received message from server {server}: {message}");
});

await _connection.StartAsync(CancellationToken.None);

这成功连接并从我的 REST API 广播接收消息(见下文)

REST API 广播

var url = $"{authenticationUtility.Endpoint}/api/v1/hubs/{hubName.ToLower()}";
var request = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri(url)
};

request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenticationUtility.GenerateAccessToken(url, sender));
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.AcceptCharset.Clear();
request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("UTF-8"));

var content = JsonConvert.SerializeObject(new MessageContent{ Target = "broadcastMessage", Arguments = new []{ sender, message}});
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);

这会像我期望的那样返回一个202 Accepted代码,并将消息发送到 .Net Core 控制台应用程序。

在我的 Azure 门户上,我能够看到连接,但我无法在我的 Web 应用程序的集线器连接中接收消息

我最终通过创建一个 .Net Core Web 应用程序来解决这个问题,该应用程序只管理集线器,然后使用(现已弃用) @aspnet/signalr npm 包连接到它。 这个包现在已经被@microsoft/signalr包替换了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM