Custom error in global.asax
In my file global.asax
, I have the following code:
void Application_Error(object sender, EventArgs e)
{
Exception TheError = Server.GetLastError();
if (TheError is HttpException && ((HttpException)TheError).GetHttpCode() == 404)
{
Response.Redirect("~/404.aspx");
}
else
{
Response.Redirect("~/500.aspx");
}
}
When I go to a page that doesn't exist, I get a generic error page. I do not want anything to do with an error in the user web.config
, because my plan is to add code to a file global.asax
for registration of exceptions. Is there a way to handle custom error with just the global.asax file?
Thank.
source to share
EDIT:
The answer is n't obvious, but it seems to explain it: http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/displaying-a-custom-error-page- cs
If you scroll down, you will find this lovely tidbit:
Note. The custom error page is displayed only when the request is executed. to a resource handled by the ASP.NET engine. ... As we discussed in the Basic Differences Between IIS and ASP.NET Development Server tutorial, a web server can handle certain requests on its own. By default, the IIS web server handles requests for static content, such as images and HTML files, without calling the ASP.NET engine. Hence, if the user requests a non-existent image file, he will return a default 404 IIS error message, not an ASP.NET customized error page.
I have highlighted the first line. I tested this in the default template, and of course this url:
http://localhost:49320/fkljflkfjelk
gets the default IIS page, whereas just adding the .aspx results in input Application_Error
. So it looks like you need to enable customErrors / httpErrors if you want all errors to be handled.
For IIS <= 6 add to <system.web>
:
<customErrors mode="On" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="/404.aspx"/>
<error statusCode="500" redirect="/500.aspx"/>
</customErrors>
For IIS7 + add to <system.webServer>
:
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="/404.aspx" responseMode="ExecuteURL"/>
<remove statusCode="500"/>
<error statusCode="500" path="/500.aspx" responseMode="ExecuteURL"/>
</httpErrors>
I'll leave the original answer in case someone finds it helpful.
I believe you need to clear the existing error code from the response, otherwise IIS will ignore your redirect in favor of handling the error. There is also a boolean flag TrySkipIisCustomErrors
, you can set for newer versions of IIS (7+).
So, something like this:
void Application_Error(object sender, EventArgs e)
{
Exception TheError = Server.GetLastError();
Server.ClearError();
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
if (TheError is HttpException && ((HttpException)TheError).GetHttpCode() == 404)
{
Response.Redirect("~/404.aspx");
}
else
{
Response.Redirect("~/500.aspx");
}
}
source to share