【问题标题】:Send Signalr message to specific user向特定用户发送 Signalr 消息
【发布时间】:2020-10-20 08:36:06
【问题描述】:

在我的项目中,我设置了 SignalR,将消息发送给连接到我网站的每个用户。我正在更改此设置,因此我的消息仅发送给生成它们的用户。但是,我无法获得我的用户身份,我希望有人能够告诉我我做错了什么/遗漏了什么。

在我的StartUp 类中,ConfigureServices 中有以下几行:

services.AddSignalR();
services.AddSingleton<IUserIdProvider, NameUserIdProvider>();
services.AddMvc(); 
services.AddAuthentication();

然后在我的Configure 我有以下几行:

app.UseAuthentication();
app.UseAuthorization();
app.UseWebSockets();
app.UseEndpoints(endpoints =>
{
  endpoints.MapHub<UserErrorHub>("/UserErrorHub", options =>
  {
    options.Transports =
       HttpTransportType.WebSockets |
       HttpTransportType.LongPolling;
  });
  endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

接下来,我的视图在&lt;script&gt; 块中设置了以下连接字符串:

 var url = "@Url.Content("~/UserErrorHub")";

    var connection = new signalR.HubConnectionBuilder()
        .withUrl(url, { transport: signalR.HttpTransportType.WebSockets | signalR.HttpTransportType.LongPolling}, options =>
        {
            options.UseDefaultCredentials = true;     
        }
        .configureLogging(signalR.LogLevel.Information)
        .build();

最后,我的中心有以下课程:

public class UserErrorHub : Hub
{
    public async override Task OnConnectedAsync()
    {
        string name;
        var user = Context.User;
        if (user.Identity.IsAuthenticated)
        {
            name = user.Identity.Name;
        }
        else
        {
            name = "anonymous";
        }
        await Clients.All.SendAsync("Message",  "hello there!" + name);
    }

    public async Task Message( string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", message);
    }
}

public class NameUserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        return connection.User?.Identity?.Name;
    }
}

当我运行我的项目时,我无法在连接时显示我的用户名,而是出现所有“匿名”,这不是我想要的。有人可以告诉我我做错了什么吗?

【问题讨论】:

    标签: javascript c# .net-core signalr signalr-hub


    【解决方案1】:

    对于我的场景,我必须删除 singalR 端点并使用旧的被弃用的方式

            app.UseSignalR(builder =>
            {
                builder.MapHub<UserErrorHub >("/userErrorHub");
            });
    

    不要忘记集线器上的 Authorize 属性

           [Authorize]
    

    【讨论】:

    • 谢谢,但这种方式现在已被贬低,并在未来的版本中被删除。所有这一切都会将问题推迟到那个时候。不过,我确实很感谢您的帮助
    • 是的,但这是我让它工作的唯一方法。当我改用端点映射时,它没有通过凭据,你试过了吗?
    • @N0xus 如果上述不正确,请尝试以下操作 var connection = new HubConnectionBuilder() .WithUrl("example.com/myhub", options => { options.UseDefaultCredentials = true; }) .Build ();
    • 不幸的是,用户名仍未通过更改。
    • 您的启动设置是否如下? “windowsAuthentication”:真,“anonymousAuthentication”:真,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2016-09-19
    • 2017-12-28
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多