asp.net - HttpContext.Current.Session 为 null + OWIN

标签 asp.net session authentication owin

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

我不明白为什么在调试时 session 为空。 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(作为空方法)。那也没有用。

我欢迎任何建议。
谢谢!

最佳答案

你是 差不多 那里。
您的 session 仍然为空的原因是您没有在执行中间件之前指示 OWIN 初始化 System.Web session 。

通过添加 .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 Middleware 在最后一个事件 (PipelineStage.PreHandlerExecute) 上运行,在这种情况下这对您来说太晚了。

现在,要使用 session ,您需要在 中工作。第二个中间件,运行 session 已被 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关于中间件的工作原理。
PiplineStage枚举文档和 HttpApplication有关 Asp.net 中执行顺序的详细信息,请参阅文档。

关于asp.net - HttpContext.Current.Session 为 null + OWIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37920879/

相关文章:

javascript - Canvasjs 图表中的渲染数据

javascript - 在 MouseOver 的 DataList ItemTemplate 内的 div 上使用 Eval?

c# - 如何在2.0构建的应用程序中使用WCF wsHttpBinding服务?

php - session 不会保存到 mysql

internet-explorer - IE 实际上并没有删除 cookie

mysql - 如何将不同类型用户的登录详细信息保存到一张表中

c# - 如何在这个简单的 asp.net webforms 应用程序中拥有和管理 session 超时?

c# - ASP.Net 删除/使 session cookie 过期

java - 为什么我的 Spring session 作用域 bean 在 session 之间共享?

java - 如何向运行 solr 的 Jetty Web 服务器添加自定义身份验证