.net – How to redirect to custom error page with specified statusCode in ASP.NET

asp.netcustom-errorsnet

I have this on my web.config:

<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
    <error statusCode="403" redirect="NoAccess.htm" />
    <error statusCode="404" redirect="FileNotFound.htm" />
<customErrors/>

How will I tell asp.net that my statusCode=404 and redirect me to NoAccess.htm?
On Global.asax Application_Error I already tried this line:

Response.StatusCode = 400

but it still redirects me to the default which is GenericErrorPage.htm.

Is there a way to explicitly set status code so that ASP.NET will redirect me to the custom error page that I want?

Best Answer

If you want to do it from global.asax, try something like the following

protected void Application_Error(object sender, EventArgs e)
{
   HttpContext ctx = HttpContext.Current;
   Exception ex = ctx.Server.GetLastError();

   if (ex is HttpRequestValidationException)
   {
       ctx.Server.ClearError();
       ctx.Response.Redirect("/validationError.htm");
   }
   else
   {
        ctx.Server.ClearError();
        ctx.Response.Redirect("/NoAccess.htm"); 
   }      
}