ASP.NET C # SuppressFormsAuthenticationRedirect doesn't work for AJAX POST?

I am calling an action in a controller decorated with a custom [ApplicationAuthorize]

via ajax POST and I want to be able to handle the case where the user is not authenticated from the ajax response, instead of redirecting ASP.NET to the login page.

I tried this one ; will not work. I am still getting 302. I also tried with attribute SuppressFormsAuthentificationRedirect

set to true when overriding HandleUnauthenticatedRequest

my custom authorization attribute function , still wont work.

Custom attribute authorize:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,
                AllowMultiple = false, Inherited = true)]
public class ApplicationAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);

        var httpContext = filterContext.HttpContext;
        var request = httpContext.Request;
        var response = httpContext.Response;
        var user = httpContext.User;

        if (request.IsAjaxRequest())
        {
            if (user.Identity.IsAuthenticated == false)
                response.StatusCode = (int)HttpStatusCode.Unauthorized;
            else
                response.StatusCode = (int)HttpStatusCode.Forbidden;

            response.SuppressFormsAuthenticationRedirect = true;
            response.End();
        }
    }
}

      

I have a working solution setting in Global.asax changing all responses with a 302-401 status when Application_EndRequest occurs, but this is temporary and not the behavior I want as sometimes the redirect is legal.

This is what I have as an answer, even with the custom authorize attribute described in this . SaveAnswer

- an action in SurveyController

called POST Ajax. Ajax POST Response

For a further understanding of the request / response pipeline of this issue, see this article.

Any ideas? I've been struggling with this issue for hours now ...

+3


source to share


1 answer


Switch the order in which you call the base class. I bet it overwrites your answer.



base.HandleUnauthorizedRequest(filterContext);
// The rest of your code

      

0


source







All Articles