我有一个Blazor应用,同时也有一个API。我有一个注入的单子,它有一些值。我的blazor应用程序上的一个页面显示了相同的单体的值。我的目标是,当我用API更新单子的值时,更新客户端正在查看的Blazore PageRazor组件。
我一直在尝试使用类似于这里的教程的signalR。https:/www.youtube.comwatch?v=1RQ_c3NPkgs
以下是我的代码。
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");
});
@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();
}
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();
}
希望能帮到你,如果你有什么问题请问。
我能够找到解决方案,但不确定为什么其他方法不能工作。
而不是使用 SendAsync
我用的是 InvokeAsync
并将方法名称传下来。有了 SendAsync
中枢没有被击中。如前所述,我不知道这是为什么。