SignalR:通知从 ASP.NET Core web API 到 Angular 7 客户端的冗长操作的进度
SignalR: notifying progress of lengthy operation from ASP.NET Core web API to Angular 7 client
已编辑:见底部
我是 SignalR 的新手,正在尝试使用此库和 ASP.NET Core web API 实现一个简单的 Angular7 客户端场景。我所需要的只是使用 SignalR 通知客户端有关 API 控制器方法中一些冗长操作的进度。
经过多次尝试,我显然已经建立了连接,但是当长任务开始 运行 并发送消息时,我的客户端似乎没有收到任何东西,也没有任何流量出现在网络套接字中(Chrome F12 - 网络 - WS)。
我在 post 此处提供详细信息,这可能对其他新手也有用(完整源代码 在 https://1drv.ms/u/s!AsHCfliT740PkZh4cHY3r7I8f-VQiQ)。可能我只是犯了一些明显的错误,但在文档和谷歌搜索中我找不到与我的有本质区别的代码片段。谁能给个提示?
我在服务器端的起点是 https://msdn.microsoft.com/en-us/magazine/mt846469.aspx, plus the docs at https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2。我试图用它创建一个虚拟实验解决方案。
我的代码片段以菜谱形式出现。
(A) 服务器端
1.create 一个新的 ASP.NET 核心网络 API 应用程序。没有身份验证或 Docker,只是为了保持最小化。
2.add NuGet 包 Microsoft.AspNetCore.SignalR
.
3.at Startup.cs
, ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
// CORS
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
// https://github.com/aspnet/SignalR/issues/2110 for AllowCredentials
.AllowCredentials()
.WithOrigins("http://localhost:4200");
}));
// SignalR
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
和对应的Configure
方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
// CORS
app.UseCors("CorsPolicy");
// SignalR: add to the API at route "/progress"
app.UseSignalR(routes =>
{
routes.MapHub<ProgressHub>("/progress");
});
app.UseHttpsRedirection();
app.UseMvc();
}
4.add 一个 ProgressHub
class,它刚好来自 Hub:
public class ProgressHub : Hub
{
}
5.add 一个 TaskController
方法开始一些冗长的操作:
[Route("api/task")]
[ApiController]
public class TaskController : ControllerBase
{
private readonly IHubContext<ProgressHub> _progressHubContext;
public TaskController(IHubContext<ProgressHub> progressHubContext)
{
_progressHubContext = progressHubContext;
}
[HttpGet("lengthy")]
public async Task<IActionResult> Lengthy([Bind(Prefix = "id")] string connectionId)
{
await _progressHubContext
.Clients
.Client(connectionId)
.SendAsync("taskStarted");
for (int i = 0; i < 100; i++)
{
Thread.Sleep(500);
Debug.WriteLine($"progress={i}");
await _progressHubContext
.Clients
.Client(connectionId)
.SendAsync("taskProgressChanged", i);
}
await _progressHubContext
.Clients
.Client(connectionId)
.SendAsync("taskEnded");
return Ok();
}
}
(B) 客户端
1.create 一个新的 Angular7 CLI 应用程序(没有路由,只是为了保持简单)。
2.npm install @aspnet/signalr --save
.
3.myapp.component
代码:
import { Component, OnInit } from '@angular/core';
import { HubConnectionBuilder, HubConnection, LogLevel } from '@aspnet/signalr';
import { TaskService } from './services/task.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
private _connection: HubConnection;
public messages: string[];
constructor(private _taskService: TaskService) {
this.messages = [];
}
ngOnInit(): void {
// https://codingblast.com/asp-net-core-signalr-chat-angular/
this._connection = new HubConnectionBuilder()
.configureLogging(LogLevel.Debug)
.withUrl("http://localhost:44348/signalr/progress")
.build();
this._connection.on("taskStarted", data => {
console.log(data);
});
this._connection.on("taskProgressChanged", data => {
console.log(data);
this.messages.push(data);
});
this._connection.on("taskEnded", data => {
console.log(data);
});
this._connection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.error('Error while establishing connection: ' + err));
}
public startJob() {
this.messages = [];
this._taskService.startJob('zeus').subscribe(
() => {
console.log('Started');
},
error => {
console.error(error);
}
);
}
}
极简主义 HTML 模板:
<h2>Test</h2>
<button type="button" (click)="startJob()">start</button>
<div>
<p *ngFor="let m of messages">{{m}}</p>
</div>
上面代码中的任务服务只是调用HttpClient
的get<any>('https://localhost:44348/api/task/lengthy?id=' + id)
.
函数的包装器
编辑 1
经过更多试验后,我进行了以下更改:
按照建议使用 .withUrl('https://localhost:44348/progress')
。似乎现在它不再触发 404。请注意更改:我将 http
替换为 https
。
不要使 API 方法异步,因为它似乎不需要 await
(即将 return 类型设置为 IActionResult
并删除 async
和 await
).
通过这些更改,我现在可以在客户端看到预期的日志消息 (Chrome F12)。看着它们,连接似乎绑定到生成的 ID k2Swgcy31gjumKtTWSlMLw
:
Utils.js:214 [2019-02-28T20:11:48.978Z] Debug: Starting HubConnection.
Utils.js:214 [2019-02-28T20:11:48.987Z] Debug: Starting connection with transfer format 'Text'.
Utils.js:214 [2019-02-28T20:11:48.988Z] Debug: Sending negotiation request: https://localhost:44348/progress/negotiate.
core.js:16828 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
Utils.js:214 [2019-02-28T20:11:49.237Z] Debug: Selecting transport 'WebSockets'.
Utils.js:210 [2019-02-28T20:11:49.377Z] Information: WebSocket connected to wss://localhost:44348/progress?id=k2Swgcy31gjumKtTWSlMLw.
Utils.js:214 [2019-02-28T20:11:49.378Z] Debug: Sending handshake request.
Utils.js:210 [2019-02-28T20:11:49.380Z] Information: Using HubProtocol 'json'.
Utils.js:214 [2019-02-28T20:11:49.533Z] Debug: Server handshake complete.
app.component.ts:39 Connection started!
app.component.ts:47 Task service succeeded
所以,我可能没有收到通知,因为我的客户端 ID 与 SignalR 分配的 ID 不匹配(根据上面引用的论文,我的印象是提供 ID 是我的责任,因为它是 API 控制器的参数)。然而,我在连接原型中看不到任何可用的方法或 属性 允许我检索此 ID,因此我可以在启动冗长的作业时将其传递给服务器。这可能是我的问题的原因吗?如果是这样,应该有一种获取 ID 的方法(或从客户端设置它)。你怎么看?
您将集线器的路由设置为 /progress
,但随后您尝试连接到 /signalr/progress
,这将是一个 404。如果您打开开发者控制台,您那里应该有一个连接错误告诉你。
看来我终于找到了。这个问题可能是由错误的ID引起的,所以我开始寻找解决方案。 post (https://github.com/aspnet/SignalR/issues/2200) 引导我使用组,在这些情况下这似乎是推荐的解决方案。因此,我更改了集线器,使其自动将当前连接 ID 分配给 "progress" 组:
public sealed class ProgressHub : Hub
{
public const string GROUP_NAME = "progress";
public override Task OnConnectedAsync()
{
// https://github.com/aspnet/SignalR/issues/2200
// https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups
return Groups.AddToGroupAsync(Context.ConnectionId, "progress");
}
}
现在,我的 API 控制器方法是:
[HttpGet("lengthy")]
public async Task<IActionResult> Lengthy()
{
await _progressHubContext
.Clients
.Group(ProgressHub.GROUP_NAME)
.SendAsync("taskStarted");
for (int i = 0; i < 100; i++)
{
Thread.Sleep(200);
Debug.WriteLine($"progress={i + 1}");
await _progressHubContext
.Clients
.Group(ProgressHub.GROUP_NAME)
.SendAsync("taskProgressChanged", i + 1);
}
await _progressHubContext
.Clients
.Group(ProgressHub.GROUP_NAME)
.SendAsync("taskEnded");
return Ok();
}
当然,我相应地更新了客户端代码,因此在调用 API 方法时不再需要发送 ID。
提供完整的演示存储库
已编辑:见底部
我是 SignalR 的新手,正在尝试使用此库和 ASP.NET Core web API 实现一个简单的 Angular7 客户端场景。我所需要的只是使用 SignalR 通知客户端有关 API 控制器方法中一些冗长操作的进度。
经过多次尝试,我显然已经建立了连接,但是当长任务开始 运行 并发送消息时,我的客户端似乎没有收到任何东西,也没有任何流量出现在网络套接字中(Chrome F12 - 网络 - WS)。
我在 post 此处提供详细信息,这可能对其他新手也有用(完整源代码 在 https://1drv.ms/u/s!AsHCfliT740PkZh4cHY3r7I8f-VQiQ)。可能我只是犯了一些明显的错误,但在文档和谷歌搜索中我找不到与我的有本质区别的代码片段。谁能给个提示?
我在服务器端的起点是 https://msdn.microsoft.com/en-us/magazine/mt846469.aspx, plus the docs at https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2。我试图用它创建一个虚拟实验解决方案。
我的代码片段以菜谱形式出现。
(A) 服务器端
1.create 一个新的 ASP.NET 核心网络 API 应用程序。没有身份验证或 Docker,只是为了保持最小化。
2.add NuGet 包 Microsoft.AspNetCore.SignalR
.
3.at Startup.cs
, ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
// CORS
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
// https://github.com/aspnet/SignalR/issues/2110 for AllowCredentials
.AllowCredentials()
.WithOrigins("http://localhost:4200");
}));
// SignalR
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
和对应的Configure
方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
// CORS
app.UseCors("CorsPolicy");
// SignalR: add to the API at route "/progress"
app.UseSignalR(routes =>
{
routes.MapHub<ProgressHub>("/progress");
});
app.UseHttpsRedirection();
app.UseMvc();
}
4.add 一个 ProgressHub
class,它刚好来自 Hub:
public class ProgressHub : Hub
{
}
5.add 一个 TaskController
方法开始一些冗长的操作:
[Route("api/task")]
[ApiController]
public class TaskController : ControllerBase
{
private readonly IHubContext<ProgressHub> _progressHubContext;
public TaskController(IHubContext<ProgressHub> progressHubContext)
{
_progressHubContext = progressHubContext;
}
[HttpGet("lengthy")]
public async Task<IActionResult> Lengthy([Bind(Prefix = "id")] string connectionId)
{
await _progressHubContext
.Clients
.Client(connectionId)
.SendAsync("taskStarted");
for (int i = 0; i < 100; i++)
{
Thread.Sleep(500);
Debug.WriteLine($"progress={i}");
await _progressHubContext
.Clients
.Client(connectionId)
.SendAsync("taskProgressChanged", i);
}
await _progressHubContext
.Clients
.Client(connectionId)
.SendAsync("taskEnded");
return Ok();
}
}
(B) 客户端
1.create 一个新的 Angular7 CLI 应用程序(没有路由,只是为了保持简单)。
2.npm install @aspnet/signalr --save
.
3.myapp.component
代码:
import { Component, OnInit } from '@angular/core';
import { HubConnectionBuilder, HubConnection, LogLevel } from '@aspnet/signalr';
import { TaskService } from './services/task.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
private _connection: HubConnection;
public messages: string[];
constructor(private _taskService: TaskService) {
this.messages = [];
}
ngOnInit(): void {
// https://codingblast.com/asp-net-core-signalr-chat-angular/
this._connection = new HubConnectionBuilder()
.configureLogging(LogLevel.Debug)
.withUrl("http://localhost:44348/signalr/progress")
.build();
this._connection.on("taskStarted", data => {
console.log(data);
});
this._connection.on("taskProgressChanged", data => {
console.log(data);
this.messages.push(data);
});
this._connection.on("taskEnded", data => {
console.log(data);
});
this._connection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.error('Error while establishing connection: ' + err));
}
public startJob() {
this.messages = [];
this._taskService.startJob('zeus').subscribe(
() => {
console.log('Started');
},
error => {
console.error(error);
}
);
}
}
极简主义 HTML 模板:
<h2>Test</h2>
<button type="button" (click)="startJob()">start</button>
<div>
<p *ngFor="let m of messages">{{m}}</p>
</div>
上面代码中的任务服务只是调用HttpClient
的get<any>('https://localhost:44348/api/task/lengthy?id=' + id)
.
编辑 1
经过更多试验后,我进行了以下更改:
按照建议使用
.withUrl('https://localhost:44348/progress')
。似乎现在它不再触发 404。请注意更改:我将http
替换为https
。不要使 API 方法异步,因为它似乎不需要
await
(即将 return 类型设置为IActionResult
并删除async
和await
).
通过这些更改,我现在可以在客户端看到预期的日志消息 (Chrome F12)。看着它们,连接似乎绑定到生成的 ID k2Swgcy31gjumKtTWSlMLw
:
Utils.js:214 [2019-02-28T20:11:48.978Z] Debug: Starting HubConnection.
Utils.js:214 [2019-02-28T20:11:48.987Z] Debug: Starting connection with transfer format 'Text'.
Utils.js:214 [2019-02-28T20:11:48.988Z] Debug: Sending negotiation request: https://localhost:44348/progress/negotiate.
core.js:16828 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
Utils.js:214 [2019-02-28T20:11:49.237Z] Debug: Selecting transport 'WebSockets'.
Utils.js:210 [2019-02-28T20:11:49.377Z] Information: WebSocket connected to wss://localhost:44348/progress?id=k2Swgcy31gjumKtTWSlMLw.
Utils.js:214 [2019-02-28T20:11:49.378Z] Debug: Sending handshake request.
Utils.js:210 [2019-02-28T20:11:49.380Z] Information: Using HubProtocol 'json'.
Utils.js:214 [2019-02-28T20:11:49.533Z] Debug: Server handshake complete.
app.component.ts:39 Connection started!
app.component.ts:47 Task service succeeded
所以,我可能没有收到通知,因为我的客户端 ID 与 SignalR 分配的 ID 不匹配(根据上面引用的论文,我的印象是提供 ID 是我的责任,因为它是 API 控制器的参数)。然而,我在连接原型中看不到任何可用的方法或 属性 允许我检索此 ID,因此我可以在启动冗长的作业时将其传递给服务器。这可能是我的问题的原因吗?如果是这样,应该有一种获取 ID 的方法(或从客户端设置它)。你怎么看?
您将集线器的路由设置为 /progress
,但随后您尝试连接到 /signalr/progress
,这将是一个 404。如果您打开开发者控制台,您那里应该有一个连接错误告诉你。
看来我终于找到了。这个问题可能是由错误的ID引起的,所以我开始寻找解决方案。 post (https://github.com/aspnet/SignalR/issues/2200) 引导我使用组,在这些情况下这似乎是推荐的解决方案。因此,我更改了集线器,使其自动将当前连接 ID 分配给 "progress" 组:
public sealed class ProgressHub : Hub
{
public const string GROUP_NAME = "progress";
public override Task OnConnectedAsync()
{
// https://github.com/aspnet/SignalR/issues/2200
// https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups
return Groups.AddToGroupAsync(Context.ConnectionId, "progress");
}
}
现在,我的 API 控制器方法是:
[HttpGet("lengthy")]
public async Task<IActionResult> Lengthy()
{
await _progressHubContext
.Clients
.Group(ProgressHub.GROUP_NAME)
.SendAsync("taskStarted");
for (int i = 0; i < 100; i++)
{
Thread.Sleep(200);
Debug.WriteLine($"progress={i + 1}");
await _progressHubContext
.Clients
.Group(ProgressHub.GROUP_NAME)
.SendAsync("taskProgressChanged", i + 1);
}
await _progressHubContext
.Clients
.Group(ProgressHub.GROUP_NAME)
.SendAsync("taskEnded");
return Ok();
}
当然,我相应地更新了客户端代码,因此在调用 API 方法时不再需要发送 ID。
提供完整的演示存储库