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

nVe*_*lia 5 c# asp.net-web-api asp.net-mvc-5

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

我环顾网络似乎表单身份验证模块正在抓取我的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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

它没有很好地工作(返回IIS Html页面).你下一步怎么做 ?

小智 9

将Cookie身份验证中间件与Web API和401响应代码一起使用 您可以通过覆盖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);
         }
     }
   }
});
Run Code Online (Sandbox Code Playgroud)

在同一个班级:

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"));
}
Run Code Online (Sandbox Code Playgroud)