我是 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/