ASP.NET MVC5 WebAPI2防止未经授权的重定向到登录页面

时间:2013-11-07 19:09:05

标签: c# asp.net-web-api asp.net-mvc-5

为什么我的WebApi2控制器在返回Unauthorized()时会将我重定向到Login页面?当我使用[Authorize]属性时也会发生同样的情况。控制器不应该按照Content-Type中的请求返回Json或XML结果吗?将我重定向到Login页面是浪费资源,对应用程序客户端完全没用。

我环顾网络似乎表单身份验证模块正在抓取我的401响应并将其转换为302.这很奇怪,因为我的身份验证模式是“无”(不是表单)。此外,我已经读过这个“功能”已在.Net 4.5(我正在运行)中修复。

我已经尝试在我的Global.asax.cs中覆盖我的Application_EndRequest

        protected void Application_EndRequest()
    {
        var context = new HttpContextWrapper(Context);
        // If we're an ajax request, and doing a 302, then we actually need to do a 401
        if (Context.Response.StatusCode == 302 && context.Request.ContentType.StartsWith("application"))
        {
            Context.Response.Clear();
            Context.Response.ClearContent();
            Context.Response.StatusCode = 401;
            context.Response.RedirectLocation = null;
            Context.Response.End();
        }
    }

它不能很好地工作(返回一个IIS Html页面)。下一步是什么?

1 个答案:

答案 0 :(得分:9)

Using cookie authentication middleware with Web API and 401 response codes 您可以通过覆盖CookieAuthenticationProvider中的OnApplyRedirect事件来自定义它。阅读博客以获得进一步的解释。

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
   AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
   LoginPath = new PathString("/Account/Login"),
   Provider = new CookieAuthenticationProvider
   {
      OnApplyRedirect = ctx =>
      {
         if (!IsAjaxRequest(ctx.Request))
         {
            ctx.Response.Redirect(ctx.RedirectUri);
         }
     }
   }
});

在同一个班级:

private static bool IsAjaxRequest(IOwinRequest request)
{
   IReadableStringCollection query = request.Query;
   if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest"))
   {
      return true;
   }
   IHeaderDictionary headers = request.Headers;
   return ((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest"));
}