ASP.NET Blazor 使用特定用户的 ASPNerUserID 更新 UI

问题描述 投票:0回答:1

SO中只有1个类似的问题,并且没有任何答案,只有意见和评论。请研究下图,它或多或少地显示了我的问题。在图片下面,我进一步解释。

enter image description here

我们有一个多项目 Web 应用程序解决方案,如上图所示。 UI 是 ASP.NET 8.0 Blazor 应用程序。为了将 UI 更新信号从逻辑项目发送到演示项目,我将一个事件发送到 AZURE 事件网格 (1),然后该事件成功传递到演示项目的 InterfaceUpdate 控制器 (2) 并进行解析 (3)。 到目前为止一切正常。

Logic Project 发送系统特定用户的 ASPNetUserID(其含义如上图所示),以便仅更新该特定用户的 UI 元素。这是要求。 我的问题是,如何使用 SignalR 通过了解特定用户的 ASPNetUserID 来更新该用户的 UI 元素?

因此,如果我想创建一个代码示例来回答这个问题,我的场景将是这样的;

  1. 创建 ASP.NET 8.0 Blazor Web 应用程序并将 SignalR 集成到管道中
  2. 创建一个继承自[ApiController]修饰的ControllerBase的InterfaceUpdate Controller,并定义一个接收webhook负载的方法。提到的 ASPNetUserID 是由逻辑项目发送的,可能属于系统中的任何人。
  3. 在 Blazor 应用程序中创建一个页面,并在 @code 部分中创建一个名为 FinalMethod 的方法。
  4. 当收到带有特定用户 ASPNetUserID 的 Webhook 时,仅针对该用户启动 FinalMethod,而不会针对可能已登录或未登录系统的其他用户启动。

请注意,我的 ASP.NET MVC 项目中已经有这个系统功能齐全!实际上它多年来一直完美工作,所以我 100% 确定这是可能的,但是我无法让它在 Blazor 中工作。在 MVC 项目中,我将我的 Hub 作为 _hobContext 注入到 webhook 控制器和 webhook 处理器方法中,解析 JSON 后,我调用“NotificationAdded”方法,该方法是 MVC 下 SignalR 的 Javascript 文件中的方法。

await _hobContext.Clients.Users(webhookJson.ASPNetUserID).SendAsync("NotificationAdded");

但是在 Blazor 中,我们没有 Javascript,所以我不知道如何使其工作,因为我们的前端是 Blazor。

感谢您花费时间和精力来解决这个问题。

c# asp.net blazor signalr
1个回答
0
投票

您需要将 userId 与 connectionId 进行比较。

在这里我注入了一个在集线器中调用的服务

OnConnectedAsync()

public class SignalHub(IClientOrchestrationService client) : Hub
{
    private readonly IClientOrchestrationService client = client;

    public override async Task OnConnectedAsync()
    {
        await base.OnConnectedAsync();
        await client.OnConnectedAsync(Context);
    }
}

此服务创建一条数据库记录,其中用户链接到连接。

public async ValueTask OnConnectedAsync(HubCallerContext context)
{
    var hubConnection = new HubConnection
    {
        UserId = context.UserIdentifier,
        ConnectionId = context.ConnectionId,
        ConnectTime = dateTimeBroker.Now(),
    };
    await this.connectionService.AddConnectionAsync(hubConnection);
    await this.SyncItemAsync<HubConnection>();
}

此代码可以注入到控制器或服务器上的其他服务中

public class HubContextBroker(IHubContext<SignalHub> hubContext) : IHubContextBroker
{
    private readonly IHubContext<SignalHub> hubContext = hubContext;

    public async ValueTask JoinGroupAsync(string connectionId, string groupName)
        => await this.hubContext.Groups.AddToGroupAsync(connectionId, groupName);

}

服务器
上的这个hubContext可用于发送消息并将用户分配到组等。

await hubContext.Clients.Group("somegroupname").SendAsync("SomeMessage");
await hubContext.Clients.Client([connectionid]).SendAsync("SomeMessage");
© www.soinside.com 2019 - 2024. All rights reserved.