Firing errors with any header status code

I spent a long time trying to get it right, so I thought it would be a good idea to post this here.

Yesterday I was creating a way to validate if the user has access to some page depending on their restrictions  that comes from a security system of the company.

Great. I created a new error page to show when the user access is denied and added it in the customErros within the Web.config.

Here is how the customErros end up like:

<customErrors mode="On" defaultRedirect="GenericError.aspx">
  <error statusCode="403" redirect="Unauthorized.aspx"/>
  <error statusCode="404" redirect="NotFound.aspx"/>      
</customErrors>

As this project is being developed using MVC I decided to implement it using the ActionFilter attributes. Here is the code:

public class CustomAuthorization : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {        
        try
        {
            // check the user
        }
        catch
        {
            // set the header but doesn't show the unauthorized page.
            // can be used to Ajax though
            //filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
            
            // redirects to GenericError
            //throw new UnauthorizedAccessException();

            // this works as excpected!
            throw new System.Web.HttpException((int)System.Net.HttpStatusCode.Forbidden, "You do not have access to that page.");
        }
        base.OnActionExecuting(filterContext);
    }
}

The last statement works the way I wanted. It fires the exception setting the header status code to 403 and redirects to my page Unathorized.aspx

I’m sure I’ve already used that HttpException before, but just to make sure I won’t forget it again, now I wrote it down.