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

Why are my AJAX requests not extending an OWIN MVC session?

我们有一个 ASP.NET MVC 5 应用程序,该应用程序一直在使用 Forms Authentication,但到期时间可滑动。我们最近切换到 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 = "/",
});

如果我单击 link 导致整个页面作为文档响应加载,但是,服务器会正​​确地扩展会话。

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

X-Responded-JSON: {"status":401,"headers":{...foo...}}

所以,我们最终只是将响应状态设置回 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;
    }

这可能是一个更可靠的解决方案:OWIN: unauthorised webapi call returning login page rather than 401