Prevent ASP.NET from redirecting to login.aspx

前端 未结 2 1544
面向向阳花
面向向阳花 2020-12-28 23:33

We have a website that runs fully on AngularJS with an ASP.NET Web API back-end with the following configuration: - HTML5 routing is enabled on Angular and there is a rewrit

相关标签:
2条回答
  • 2020-12-29 00:12

    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();
        }
    });
    
    0 讨论(0)
  • 2020-12-29 00:24

    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;
    }
    
    0 讨论(0)
提交回复
热议问题