ASP.NET MVC forces an AJAX request be redirected t

2019-03-11 06:51发布

问题:

I have some AJAX calls that render PartialViewResults via the jQuery.AJAX method. This works great, I get my views rendered exactly the way I want.

The problem arises when I leave the page up for a while and the Forms auth session expires. When I click an action that performs an AJAX request, it shows the login page in my div.

I want it to redirect the WHOLE page to the login page.

回答1:

Set it up in the Application_EndRequest() method of the Global.asax

You can check to see if the request is an ajax request and also check if it is sending an HTTP redirect (302) if it is, then we actuall want to send a 401.

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

Then in your client code, in a globally accessible area:

MyNamespace.handleAjaxError = function (XMLHttpRequest, textStatus, errorThrown) {
    if (XMLHttpRequest.status == 401) {
        // perform a redirect to the login page since we're no longer authorized
        window.location.replace("logout path");
    }    
    } else {
        MyNamespace.displayGeneralError();
    }
};

  $.ajax({
  type: "GET",
  url: userAdmin.addUserActionUrl,
  success: userAdmin.createUserEditorDialog,
  error: MyNamespace.handleAjaxError
 });


回答2:

With current versions of ASP.NET MVC there is a much easier solution to fix this issue: Response.SuppressFormsAuthenticationRedirect.

You can apply this in your Global.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContextWrapper context = new HttpContextWrapper(this.Context);

    if (context.Request.IsAjaxRequest())
    {
        context.Response.SuppressFormsAuthenticationRedirect = true;
    }
}


回答3:

When I have FormsAuthentication in place, I will include the Login URL in the answer https://stackoverflow.com/a/3431350/1559213 provided by @Chris Kooken

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.RedirectLocation.Contains(FormsAuthentication.LoginUrl))
        {
            Context.Response.Clear();
            Context.Response.StatusCode = 401;
        }
    }