Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET MVC5 WebAPI2防止未经授权重定向到登录页面_C#_Asp.net Web Api_Asp.net Mvc 5 - Fatal编程技术网

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

C# ASP.NET MVC5 WebAPI2防止未经授权重定向到登录页面,c#,asp.net-web-api,asp.net-mvc-5,C#,Asp.net Web Api,Asp.net Mvc 5,当我返回Unauthorized()时,为什么我的WebApi2控制器会将我重定向到登录页面?使用[Authorize]属性时也会发生同样的情况。控制器不应该按照内容类型中的请求返回Json或XML结果吗?将我重定向到登录页面是一种浪费资源的行为,对应用程序客户端来说完全没有用处 我环顾了一下网络,似乎表单验证模块正在抓取我的401响应并将其转换为302。这很奇怪,因为我的身份验证模式是“无”(而不是表单)。此外,我还了解到,该“功能”已在.NET4.5(我正在运行)中修复 我已尝试在我的Glo

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

我环顾了一下网络,似乎表单验证模块正在抓取我的401响应并将其转换为302。这很奇怪,因为我的身份验证模式是“无”(而不是表单)。此外,我还了解到,该“功能”已在.NET4.5(我正在运行)中修复

我已尝试在我的Global.asax.cs中覆盖我的应用程序\u 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页面)。下一步是什么?

您可以通过覆盖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"));
}

谢谢,您已经尽力了。无法让SuppressFormsAuthenticationRedirect在同时使用mvc和webapi的项目中工作,使用OnApplyRedirect检查安全标头就成功了!可能重复的