HttpContext.Current.Session为null + OWIN [英] HttpContext.Current.Session is null + OWIN

查看:292
本文介绍了HttpContext.Current.Session为null + OWIN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OWIN的新手,这个问题对我来说是一个主要的障碍.

I'm entirely new to OWIN and this issue has been a major blocker for me.

基本上,在我的MVC应用程序中,我在Startup类中具有以下内容:

Basically, at my MVC app I have the following at Startup class:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = OfficeSettings.ClientId,
                    Authority = OfficeSettings.Authority,

                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        RoleClaimType = "roles"
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {

                    AuthorizationCodeReceived = (context) =>
                        {
                        // code hidden for readability

                            if(HttpContext.Current.Session == null)
                            {
                                // It's null. Why is that?
                            }

                            var session = HttpContext.Current.Session;
                            if (session["myMockSession"] != null)
                            {
                                // Do stuff...
                            }
                        },

                        RedirectToIdentityProvider = (context) =>
                        {
                            // code hidden for readability
                        },

                        AuthenticationFailed = (context) =>
                        {
                            // code hidden for readability
                        }
                    }
                });

当我调试Session为null时,我不明白为什么. HttpContext.Current属性不是. Sessions + OWIN是否有任何限制?有没有解决此问题的方法?一个应该如何处理?

I don't understand why when I'm debugging that the Session is null. HttpContext.Current Property isn't. Are there any constraints with Sessions + OWIN? Is there any workaround for this issue? How should one approach it?

注释1: 我试图添加在一个SO问题中找到的这段代码,但Session仍然为空:

Side note 1: I've tried to add this piece of code I've found in one of the SO questions and the Session was still null:

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

注释2: 我似乎再也找不到它了,但是有人在一个SO问题中建议在Global.asax上添加空方法Session_Start和Session_End(作为空方法).那也不行.

Side note 2: I don't seem to find it anymore, but someone suggested in one of the SO questions to add empty methods Session_Start and Session_End (as empty methods) at the Global.asax. That didn't worked neither.

我欢迎任何建议. 谢谢!

I'm welcoming any advises. Thanks!

推荐答案

您在那里快要了. 会话仍然为空的原因是您没有指示OWIN在执行中间件之前先初始化System.Web会话.

You're almost there. The reason your session is still null is that you have not instructed OWIN to initialize System.Web Sessions prior to your middleware is beeing executed.

在中间件注册之后,通过添加 .UseStageMarker(..) ,您将告诉OWIN它应该在执行管线中的哪个位置执行 SetSessionStateBehaviour

By adding .UseStageMarker(..) after your middleware registration you'll tell OWIN where in the execution pipline it should perform SetSessionStateBehaviour

app.Use((context, next) =>
{
    var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
    httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
    return next();
});

// To make sure the above `Use` is in the correct position:
app.UseStageMarker(PipelineStage.MapHandler);

默认情况下,Owin中间件在最后一个事件(PipelineStage.PreHandlerExecute)上运行,这种情况对您来说太晚了.

By default, Owin Middleware run at the last event (PipelineStage.PreHandlerExecute) which is too late for you in this case.

现在,要使用会话,您需要在中间件中工作,该中间件在Asp.Net运行库已获取会话后后运行.该中间件必须在 PostAquireState 阶段中运行,如下所示:

Now, to use sessions, you need to work in a second middleware, that runs after the session has been Aquired by the Asp.Net runtime. This middleware must be run in the PostAquireState phase, like so:

.Use((context, next) =>
 {
     // now use the session
     HttpContext.Current.Session["test"] = 1;

     return next();
})
.UseStageMarker(PipelineStage.PostAcquireState);

Asp.Net katana文档有一个关于中间件如何工作的优秀文章. 请参见 PiplineStage 枚举文档和 HttpApplication 文档,以获取有关Asp.net中执行顺序的详细信息.

Asp.Net katana docs has an excellent article on how the middleware works. See the PiplineStage enum docs and the HttpApplication docs for details on the execution order in Asp.net.

这篇关于HttpContext.Current.Session为null + OWIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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