Friday 30 August 2013

Custome Error 404 Page

Its been hard stuff to handle 404 error in our web application. I found one good solution. I would like to share with you.

Detecting HTTP 404 Errors in Global.asax

While I realize this is a simple task and once you see how to do it you will immediately say, I knew that, but for those of you who have not discovered how to detect http 404 errors let me show you.
The following code may be inserted into your Global.asax file.

protected void Application_Error(object sender, EventArgs e)
{
Exception ex = null;
if (HttpContext.Current.Server.GetLastError() != null)
{
ex = HttpContext.Current.Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(HttpException))
{
HttpException httpException = (HttpException)ex;
if (httpException.GetHttpCode() == 404)
{
Server.Transfer(“~/ErrorPage.htm”);
return;
}
}
}

The above code if placed into you Global.asax file will intercept Http 404 errors and transfer to your page that handles that particular error.  You may also check for any other particular http error and transfer to another page if you choose.
You see, it is a simple task, now that you know how.


You can also do it another way
In WebConfig


 <customErrors mode="On"  defaultRedirect="http://localhost:60876/ErrorPage.htm">     
      <error statusCode="403" redirect="http://localhost:60876/ErrorPage.htm" />
      <error statusCode="404" redirect="http://localhost:60876/ErrorPage.htm" />
  </customErrors>