我们正在使用我们的webapi的dotnet 6。
我们已经使用了身份验证,并在HttpContext中获取所有用户数据。
但是,无法在SignalR上下文中设置此数据。
builder.Services.AddSignalR(configure =>
{
configure.MaximumReceiveMessageSize = null;
configure.EnableDetailedErrors = true;
});
=============
app.UseHttpStatusCodeMiddleware();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseHttpsRedirection();
app.MapControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/hubs/chat");
});
发布于 2022-10-03 03:21:20
SignalR连接不同于一般的请求,它是由websocket构建的。
SignalR中的单个用户可以有多个连接到一个应用程序。例如,用户可以在他们的桌面和手机上连接。每个设备都有一个单独的SignalR连接,但它们都与同一个用户相关联。如果将消息发送给用户,则与该用户关联的所有连接都会收到该消息。连接的用户标识符可以由集线器中的Context.UserIdentifier属性访问。
默认情况下,SignalR使用与连接关联的ClaimTypes.NameIdentifier作为用户标识符。
因此,如果您想使用用户名,可以尝试使用User.FindFirst(ClaimTypes.NameIdentifier).Value
。
此外,如果您想修改userid,您应该像这样定制IUserIdProvider并将其注册为单例。
public class UserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
return connection.User.FindFirst(ClaimConstants.PreferredUserName).Value;
}
}
https://stackoverflow.com/questions/73910140
复制相似问题