HttpStatusCodeResult(401)返回"302 Found"

Ada*_*abo 10 c# asp.net asp.net-mvc http-status-codes asp.net-mvc-5

使用ASP.NET MVC 5,我想为不同的场景返回适当的HTTP状态代码(401用户未经过身份验证,403当用户无权使用某些资源时等),而不是在jQuery中处理它们.

但问题是,当我尝试返回401时,它总是返回"302:Found".自定义状态代码的技巧是什么,以及为什么这不起作用?

public ActionResult My()
{
    if (User.Identity.IsAuthenticated == false)
    {
        return new HttpStatusCodeResult(401, "User is not authenticated."); 
            // Returns "302: Found"
    }

   // ... other code ...
}
Run Code Online (Sandbox Code Playgroud)

编辑1:有趣的位:

如果我用这样的404替换401:

return new HttpNotFoundResult("User is not authenticated.");
Run Code Online (Sandbox Code Playgroud)

然后它确实给出了404和jQuery可以捕获的问题.然而,由于错误代码不同,它不是一个优雅的解决方案.

编辑2: 302对我不好,因为结果将被使用jQuery.get().fail(),但302将不会消失fail()

Not*_*ple 18

大声笑这是一个很棒的问题

auth在MVC中的工作方式是,当您未登录并尝试访问安全页面时,它会抛出401异常.MVC然后捕获此异常并将用户重定向到登录页面(这是您看到的302)

我想你可以采取一些措施来解决它:

  • 忽略它,它可能是你想要的行为
  • 禁用登录页面重定向(phil haack在这里有一篇很好的文章:http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want .aspx)

编辑

根据您的评论,以下代码将通过ajax请求将所有重定向转换为401.这是避免列出问题的一种方法

public class MvcApplication : HttpApplication {
    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.IsAjaxRequest()) {
            Context.Response.Clear();
            Context.Response.StatusCode = 401;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ user2270404如果您的目标是.net 4.5,它只是`Response.SuppressFormsAuthenticationRedirect = true` (4认同)