HttpStatusCodeResult(401) returns “302 Found”

后端 未结 1 1421
遥遥无期
遥遥无期 2020-12-16 18:33

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 reso

1条回答
  •  囚心锁ツ
    2020-12-16 19:07

    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:

    • Ignore it, its probably the behaviour you want anyway
    • Disable login page redirection (phil haack has a good article on this here: http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx)

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

    0 讨论(0)
提交回复
热议问题