Search code examples
.netasp.net-mvchttp-status-code-403action-filterasp.net-authorization

Incorrect message coming when sending 403 status code after hosting on IIS


I have created a custom authorization filter in my .net MVC application for role-based authorization. I am sending 403 status code and custom error message when the user is not authorized in handleunauthorizedRequest method (please see the code below)

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
        {
            filterContext.HttpContext.Response.StatusCode =(int) HttpStatusCode.Forbidden;
            filterContext.HttpContext.Response.Write("Not Authorized");
            filterContext.Result = new EmptyResult();
            //filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Not Authorized");

        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }


    }

I am getting the correct error message ("Not Authorized") when running the application on the localhost. However, after making the application live in the IIS server, I was getting the default error page for 403 status code so I removed the default error page for 403 status from IIS. Now I am getting the below error message :

You do not have permission to view this directory or page.

Can anyone please tell me where is this message coming from?


Solution

  • I am able to solve this after reading a few blogs and Microsoft docs. I have added the below line in my web.config file to keep the response untouched

     <httpErrors existingResponse="PassThrough" />
    

    You can read about httpErros here: microsoft docs