Search code examples
asp.netauthorizationasp.net-web-apicustom-error-pages

HandleUnauthorizedRequest in ASP.Net Web API


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.