【问题标题】:How to control SignalR from an API Endpoint如何从 API 端点控制 SignalR
【发布时间】: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


    【解决方案1】:

    我能够找到解决方案,但不确定为什么其他方法不起作用。

    我没有使用SendAsync,而是使用InvokeAsync 并传递了方法名称。使用SendAsync,集线器没有被击中。如前所述,我不知道这是为什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 2018-11-27
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多