【发布时间】:2020-08-06 07:03:35
【问题描述】:
我有一个 Blazor 应用程序,同时也有一个 API。我有一个注入的单例,它有一些值。我的 blazor 应用程序上的页面显示相同的单例值。我的目标是在我使用 API 更新单例值时更新客户端正在查看的 Blazore 页面/Razor 组件。
我一直在尝试使用与教程类似的 signalR:https://www.youtube.com/watch?v=1RQ_c3NPkgs
下面是我的代码:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// All other services
...
// Signal R
app.AddSignalR();
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
endpoints.MapHub<MessageHub>("/_MessageHub");
});
Blazor 页面
@using Marel.LairageScanner.Services.Interfaces
@using Microsoft.AspNetCore.SignalR.Client
@using Marel.LairageScanner.BlazorApp.Data.Communication
@inject IPenService penService
<b>Message Retrieved : @penService.CurrentPen</b><br>
<b>Connection State : @connectionState</b>
@code {
private HubConnection hubConnection;
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl("https://localhost:44332/_MessageHub")
.Build();
hubConnection.On(MessageCommand.Update, UpdateState);
await hubConnection.StartAsync();
}
void UpdateState() => StateHasChanged();
}
API 端点
private readonly IPenService penService;
private readonly HubConnection hubConnection;
public ScannerController(penService)
{
this.penService = penService;
// Initalize thi hub controller
hubConnection = new HubConnectionBuilder()
.WithUrl("https://localhost:44332/_MessageHub")
.Build();
}
[HttpPut("{value}")]
public async Task<IActionResult> SetValue(
[FromRoute] string value,
CancellationToken cancellationToken)
{
penService.CurrentPen = value;
await hubConnection.StartAsync();
await hubConnection.SendAsync(MessageCommand.Update);
await hubConnection.StopAsync();
return Ok();
}
希望对你有帮助,如果有任何问题,请提出。
【问题讨论】:
标签: signalr blazor signalr-hub