我为ASP.NET和SignalR复制了一些代码,因此决定将其重写为OWIN中间件,以删除此重复项。
运行HttpContext.Current.Session
完它后,我注意到它为null,并且在IOwinContext
中间件上没有看到任何会话对象。
是否可以从OWIN访问http会话?
是的,但这是一个hack。它也不适用于SignalR,因为SignalR必须在获取会话之前运行,以防止长时间的会话锁定。
这样做可以为任何请求启用会话:
public static class AspNetSessionExtensions
{
public static IAppBuilder RequireAspNetSession(this IAppBuilder app)
{
app.Use((context, next) =>
{
// Depending on the handler the request gets mapped to, session might not be enabled. Force it on.
HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
return next();
});
// SetSessionStateBehavior must be called before AcquireState
app.UseStageMarker(PipelineStage.MapHandler);
return app;
}
}
然后,您可以使用HttpContext.Current.Session
或来访问会话
HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句