Prevent ASP.NET from redirecting to login.aspx

If you are using ASP.NET 4.5. you can disable forms authentication redirect HttpResponse.SuppressFormsAuthenticationRedirect property.

In Global.asax:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
        HttpApplication context = (HttpApplication)sender;
        context.Response.SuppressFormsAuthenticationRedirect = true;
}

In summary, i've put this in global.asax

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var context = new HttpContextWrapper(Context);
    // set flag only if forms auth enabled and request comes from ajax
    if (FormsAuthentication.IsEnabled && context.Request.IsAjaxRequest())
    {
        context.Response.SuppressFormsAuthenticationRedirect = true;
    }
}

and for IsAjaxRequest() used this

public static bool IsAjaxRequest(this HttpRequestBase request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }
    var context = HttpContext.Current;
    var isCallbackRequest = false;// callback requests are ajax requests
    if (context != null && context.CurrentHandler is Page)
    {
        isCallbackRequest = ((Page)context.CurrentHandler).IsCallback;
    }
    return isCallbackRequest || request["X-Requested-With"] == "XMLHttpRequest" || 
        request.Headers["X-Requested-With"] == "XMLHttpRequest";
}

so for every ajax request forms auth will not be redirect anymore. It's the best solution that i've found.

And optionally, put this in client code, for page reload after receiving 401 error answers.

$(document).ajaxError(function (xhr, props) {
    if (props.status === 401) {
        location.reload();
    }
});