[SOLVED] HandleUnauthorizedRequest in ASP.Net Web API

Issue

I am developing a ASP.Net Web API application and I have used AuthorizeAttribute for the authentication. When the authentication fails, the code that executes is this.

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
        return;
    }

This code results to display a Unauthorized request page from the browser but what I want is to display a custom page which I have designed. How do I do that?

Solution

I don’t think you can redirect to your custom page from within HandleUnathorizedRequest if you are using WebApi. The code result displays Unauthorized request page because that is how your browser responds to 403 code. WebApi works on HttpMessage exchange and by default uses either Json or Xml media type. If you want to return your customized page as text/html then you will have to write your own media formatter as explained here: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters.

Answered By – Bijay Kusle

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *