为什么我的AJAX请求不扩展OWIN MVC会话

本文关键字:OWIN MVC 会话 扩展 我的 AJAX 请求 为什么 | 更新日期: 2023-09-27 18:18:00

我们有一个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 = "/",
});

如果我单击一个链接,导致整个页面作为文档响应加载,但是,服务器适当地扩展会话

为什么我的AJAX请求不扩展OWIN MVC会话

我最终做出了一些错误的假设。AJAX请求正在扩展。 200的返回让我感到困惑。在使用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:未经授权的webapi调用返回登录页面而不是401