Unified static class between HttpContext and SignalR HubCallerContext

前端 未结 2 1016
醉梦人生
醉梦人生 2021-01-01 21:41

I have a lot of code that depends on HttpContext.Current, and I noticed that requests that come from SignalR hubs have HttpContext.Current == null, so my code b

2条回答
  •  -上瘾入骨i
    2021-01-01 22:17

    Just spent a couple of hours on this problem.

    It looks like there is no way to get SignalR context outside of hub class in the same manner like you would do this with HttpContext:

    var identity = HttpContext.Current.User.Identity;
    

    or inside Ninject context:

    HttpContextBase httpContext = context.Kernel.Get();
    var identity = httpContext.Current.User.Identity;
    

    At least the answer to this question states so: Get SignalR User (Hub.Context) outside of hub.

    But in this particular case when you need to get current user identity there is a solution which works in both worlds: WebApi/MVC and SignalR.

    IPrincipal principal = Thread.CurrentPrincipal;
    var identity = principal.Identity;
    

    I used this to get user identity inside my dependency injection code.

    Morover, Context property is only available in hub methods (it is null inside hub constructor). But Thread.CurrentPrincipal.Identity will give you the user identity even inside hub constructor.

提交回复
热议问题