Tutorial :custom 404 page with asp.net C# 3.5 on IIS6



Question:

for error handling I have a few lines of code for catching every error in the global.asax : void Application_Error(object sender, EventArgs e) the content of the function looks like this:

try      {         Exception objErr = Server.GetLastError().GetBaseException();           if (!(objErr is HttpException))         {             shop.BLL.Utility.Errorlog.WriteError(objErr, "Global.asax caught an Exception");         }         else         {             HttpException hex = (HttpException)objErr;             if (hex.ErrorCode == 404)                 Response.Redirect("404.aspx?msg=" + hex.Message);             else             {                 shop.BLL.Utility.Errorlog.WriteError(hex, "Global.asax caught an HttpException code: " + hex.ErrorCode);             }         }        }      catch { }        Server.ClearError();  

now here is the thing: when I go to blabla.aspx, which does not exists, it ends up on line shop.BLL.Utility.Errorlog.WriteError(hex, "Global.asax caught an HttpException code: " + hex.ErrorCode); and the value of the errorcode is -2147467259

Why isn't it a 404?


Solution:1

I think you should check with GetHttpCode() method.

 HttpException hex = (HttpException)objErr;   if (hex.GetHttpCode() == 404)       Response.Redirect("404.aspx?msg=" + hex.Message);  


Solution:2

The page not found doesn't throw an exception, the 404 error is an Http response code. If you are trying to set up a custom error page for 404 handling, you can set it up using the

<customErrors>  

tag in your web.config

have a look at these articles...

http://aspnetresources.com/articles/CustomErrorPages and http://www.asp.net/hosting/tutorials/displaying-a-custom-error-page-cs

Dave


Solution:3

From MSDN docs:

ErrorCode Gets the HRESULT of the error. (Inherited from ExternalException).

GetHttpCode() Gets the HTTP response status code to return to the client.

The HRESULT 0x80004005 means Generic Error.


Solution:4

I don't think you want to use ErrorCode - that is for the internal error. Try using GetHttpCode() on your HttpException object. That should return the 404 you are looking for.

if (hex.GetHttpCode() == 404)  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »