OWIN中间件可以使用http会话吗? [英] Can OWIN middleware use the http session?

查看:119
本文介绍了OWIN中间件可以使用http会话吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要为ASP.NET和SignalR复制的代码,因此我决定将其重写为OWIN中间件,以消除此重复.

I had a little bit of code that I was duplicating for ASP.NET and SignalR and I decided to rewrite it as OWIN middleware to remove this duplication.

运行后,我注意到HttpContext.Current.Session为空,并且在中间件上的IOwinContext上没有看到任何会话对象.

Once I was running it I noticed that HttpContext.Current.Session was null, and I didn't see any session object on the IOwinContext that my middleware has.

是否可以从OWIN访问http会话?

Is it possible to access the http session from OWIN?

推荐答案

是的,但这确实是一个hack.它也不适用于SignalR,因为SignalR必须在获取会话之前运行,以防止长时间的会话锁定.

Yes, but it's quite a hack. It also won't work with SignalR because SignalR MUST run before session is acquired to prevent long session locks.

执行此操作以为任何请求启用会话:

Do this to enable session for any request:

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);

这篇关于OWIN中间件可以使用http会话吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆