Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c# - HttpStatusCodeResult(401) returns "302 Found"

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.

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

EDIT 1: Interesting bit:

If I replace the 401 with a 404 like this:

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

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 is not good for me, as the result would be used in jQuery.get().fail(), but 302 won't triger fail()

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lol this is an awesome problem

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:

EDIT

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...