【问题标题】:HttpContext.Current.Session is null + OWINHttpContext.Current.Session 为 null + OWIN
【发布时间】:2016-10-21 14:41:31
【问题描述】:

我是 OWIN 的新手,这个问题一直是我的主要障碍。

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

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

我不明白为什么在调试时会话为空。 HttpContext.Current 属性不是。 Sessions + OWIN 有什么限制吗?这个问题有什么解决方法吗?应该如何处理它?

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

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(作为空方法)。那也没有用。

我欢迎任何建议。 谢谢!

【问题讨论】:

  • 我有类似的问题。你能找到一些解决办法吗?
  • 嗨@RonakThakkar。不幸的是,还没有。我不得不把这项任务放在一边,因为我找不到任何解决方案。也许我们可以在这个线程中得到一个解决方案,希望如此。
  • 您好 AuroMetal,感谢您发布这个问题。我一直试图让它工作,但我不确定在哪里插入@Johan O 的解决方案。如果有人能提供更多细节,我将不胜感激。
  • 嗨@AP,如果我理解正确,您是在问将此代码放在哪里?请记住,这个问题已经超过 2 年了,但我相信当您创建一个 ASP.NET Web 应用程序 > MVC 模板(更改身份验证 - 个人用户 || 工作或学校帐户)时,会创建一个 App_Start 目录,并且在它下面有一个 Startup.Auth.cs ,它是您插入解决方案的地方。再说一次,时间太长了,我可能错了,所以提前道歉。

标签: asp.net session authentication owin


【解决方案1】:

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

通过添加 .UseStageMarker(..) 您的中间件注册之后,您将告诉 OWIN 它应该在执行管道中的哪个位置执行 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) 处运行,在这种情况下对您来说太迟了。

现在,要使用会话,您需要在 第二个 中间件中工作,该中间件在 会话被 Asp.Net 运行时获取之后运行。此中间件必须在 PostAquireState 阶段运行,如下所示:

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

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

Asp.Net katana 文档有一个excellent article 说明中间件的工作原理。 有关 Asp.net 中执行顺序的详细信息,请参阅 PiplineStage 枚举文档和 HttpApplication 文档。

【讨论】:

  • 嗨@Johan O,绝对精彩的解释!非常感谢您提供的详细信息,希望这能帮助我们中的一些人解决同样的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2013-05-21
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多