public class UserCircuitHandler : CircuitHandler { private readonly IHttpContextAccessor _httpContextAccessor; public UserCircuitHandler(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public override async Task OnConnectionUpAsync(Circuit circuit, CancellationToken cancellationToken) { var httpContext = _httpContextAccessor.HttpContext; var userAgent = httpContext.Request.Headers["User-Agent"]; string uaString = userAgent.ToString(); var uaParser = Parser.GetDefault(); ClientInfo c = uaParser.Parse(uaString); Console.WriteLine(httpContext.User.Identity.Name); } public override async Task OnConnectionDownAsync(Circuit circuit, CancellationToken cancellationToken) { var httpContext = _httpContextAccessor.HttpContext; var userAgent = httpContext.Request.Headers["User-Agent"]; string uaString = userAgent.ToString(); var uaParser = Parser.GetDefault(); ClientInfo c = uaParser.Parse(uaString); Console.WriteLine(httpContext.User.Identity.Name); } }
References
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/signalr?view=aspnetcore-7.0#blazor-server-circuit-handler
https://learn.microsoft.com/en-us/aspnet/core/blazor/security/server/additional-scenarios?view=aspnetcore-7.0#circuit-handler-to-capture-users-for-custom-services