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

查看:42
本文介绍了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?

推荐答案

是的,但它是一个黑客.它也不适用于 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

Then you can access the session with either HttpContext.Current.Session or

HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);

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

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