之间的HttpContext和SignalR HubCallerContext统一静态类 [英] Unified static class between HttpContext and SignalR HubCallerContext
问题描述
我有很多code的依赖HttpContext.Current,
我注意到了来自SignalR枢纽请求有 HttpContext.Current == NULL
,
所以我的code减免,例如:
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 breaks, for example:
HttpContext.Current.Request.IsAuthenticated
于是我想出了以下内容:
So I came up with following:
public static class UnifiedHttpContext
{
private static HubCallerContext SignalRContext { get; set; }
private static int SignalRUserId
{
get { return WebSecurity.GetUserId(SignalRContext.User.Identity.Name); }
}
private static bool IsSignalRRequest
{
get { return SignalRContext != null; }
}
public static void SetSignalRContext(HubCallerContext context)
{
SignalRContext = context;
}
public static bool IsAuthenticated
{
get
{
if (!IsSignalRRequest)
{
return System.Web.HttpContext.Current.Request.IsAuthenticated;
}
else
{
return SignalRContext.User.Identity.IsAuthenticated;
}
}
}
public static int UserId
{
get
{
if (!IsSignalRRequest)
{
return WebSecurity.CurrentUserId;
}
else
{
return SignalRUserId;
}
}
}
}
和在主枢纽(每隔枢纽从它继承):
And in master hub (every other hub inherits from it):
public abstract class MainHub : Hub
{
public override Task OnConnected()
{
UnifiedHttpContext.SetSignalRContext(Context);
Groups.Add(Context.ConnectionId, UnifiedHttpContext.UserId.ToString());
return base.OnConnected();
}
}
-
这是正确的做法,或者是这个解决在某种程度上,我是不知道的?
Is this correct approach, or is this solved somehow already that I'm not aware of?
这是危险的,因为静态类在应用程序共享的,会为所有用户设置这同样的情况下?如果是这样,我可以让每个请求?
Is this dangerous since static classes are shared in application, would this set same context for all users? If so can I make it per request?
推荐答案
SignalR可以访问
HubCallerContex
而不是的HttpContext
。您可以通过使用关键字背景
访问HubCallerContext对象。如果您要访问的HttpContext
则可以按照以下方法从上下文中获取它:SignalR gives you access to
HubCallerContex
instead ofHttpContext
. You can access HubCallerContext object by using keywordcontext
. If you want to accessHttpContext
you can fetch it from the context as follows:System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext();
希望这有助于。
这篇关于之间的HttpContext和SignalR HubCallerContext统一静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!