为什么我的AJAX请求没有扩展OWIN MVC会话?

rar*_*rrr 12 c# ajax asp.net-mvc session-timeout owin

我们有一个ASP.NET MVC 5应用程序,它一直使用带有滑动过期的表单身份验证.我们最近切换到OWIN Cookie身份验证,并且遇到了我们的会话无法正常扩展的问题.

以前,可以从AJAX xhr请求扩展会话.但是,使用此配置,它们不会扩展.即使在服务器终止会话之后,我也会收到应该扩展的每个请求(GET和POST)的200.

目前的设置是:

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
   AuthenticationType = "Cookies",
   CookieSecure = CookieSecureOption.SameAsRequest,
   CookieName = Constants.CatalystPortalCookieName,
   LoginPath = new PathString(url.Action(nameof(LoginController.Index), "Login")),
   SlidingExpiration = true,
   ExpireTimeSpan = TimeSpan.FromMinutes(20),
   CookiePath = "/",
});
Run Code Online (Sandbox Code Playgroud)

但是,如果单击导致整个页面作为文档响应加载的链接,则服务器会正​​确扩展会话.

rar*_*rrr 0

我最终得出了一些错误的假设。AJAX 请求正在扩展。200的回归让我很失望。在使用 fiddler 查看实际响应后,我发现随着 OWIN 的更改,401 实际上在响应中移动了:

X-Responded-JSON: {"status":401,"headers":{...foo...}}
Run Code Online (Sandbox Code Playgroud)

所以,我们最终只是将响应的状态设置回 401。这可能很糟糕,但它符合我们的需求。

protected void Application_EndRequest() {
    var context = new HttpContextWrapper(Context);
    var header = context.Response.Headers["X-Responded-JSON"];
    if (header != null && header.Contains("\"status\":401")) {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
Run Code Online (Sandbox Code Playgroud)

这可能是一个更强大的解决方案: OWIN:未经授权的 webapi 调用返回登录页面而不是 401