HttpStatusCodeResult(401) 返回“302 Found" [英] HttpStatusCodeResult(401) returns "302 Found"

查看:40
本文介绍了HttpStatusCodeResult(401) 返回“302 Found"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using ASP.NET MVC 5, I would like to return appropriate HTTP status code for different scenarios (401 for user is not authenticated, 403 when user has no right for some resource, etc.), than handle them in jQuery.

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

But the problem is, when I try to return 401, it always returns "302: Found". What is the trick for a custom status code, and why this doesn't work?

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

   // ... other code ...
}

编辑 1:有趣的一点:

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

If I replace the 401 with a 404 like this:

return new HttpNotFoundResult("User is not authenticated.");

然后它确实给出了 404 并且 jQuery 可以解决问题.然而,这不是一个优雅的解决方案,因为错误代码不同.

Then it indeed gives a 404 and jQuery can catch the problem. However it's not an elegant solution as the error code is different.

EDIT 2: 302 对我不好,因为结果将用于 jQuery.get().fail(),但 302 不会触发fail()

EDIT 2: 302 is not good for me, as the result would be used in jQuery.get().fail(), but 302 won't triger fail()

推荐答案

Lol 这是一个很棒的问题

Lol this is an awesome problem

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

The way auth works in MVC is that when you aren't logged in and try to access a secure page it throws a 401 exception. MVC then catches this exception and redirects the user to the login page (which is the 302 you are seeing)

我想你可以做一些事情来修复它:

I suppose there's a few things you can do to fix it:

编辑

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

As per your comments, the following code will turn all redirects into 401s when requested via ajax. This is one approach for avoiding the issue listed

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;
        }
    }
}

这篇关于HttpStatusCodeResult(401) 返回“302 Found"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆