ASP.NET MVC Authorize Attribute does a 302 redirect when the user is not authorized

前端 未结 4 2052

MSDN explicitly says it should do 401 redirect, but I\'m getting a 302 redirect on FF, and this is causing problems in AJAX requests as the returned status is 200 (from the red

4条回答
  •  隐瞒了意图╮
    2021-02-04 09:46

    I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective.

    Global.asax:

    protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 302 &&
            Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            Context.Response.Clear();
            Context.Response.StatusCode = 401;
        }
    }
    

    Client Side Code:

     $(function () {
          $.ajaxSetup({
            statusCode: {
              401: function () {
                location.href = '/Logon.aspx?ReturnUrl=' + location.pathname;
              }
            }
          });
        });
    

提交回复
热议问题