【发布时间】: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?}");
});
接下来,我的视图在<script> 块中设置了以下连接字符串:
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