开发者

In ASP.NET how to identify/process 404 exceptions?

I need to handle 404 exceptions differently than all other types of them. What is the best way to identify those 404 exceptions (dis开发者_运维技巧tinguish them from other exceptions)?

The problem is that there is no a special exception class for 404 errors, I get regular System.Web.HttpException with Message = "File does not exist."

Should I just use exception's message for it or is there a better way?

Thank you.


You can try to cast the exception as an HttpException, and then use the GetHttpCode method to check whether it is a 404 or not.

For example:

Exception ex = Server.GetLastError();

HttpException httpEx = ex as HttpException;

if (httpEx != null && httpEx.GetHttpCode() == 404)
{
   //do what you want for 404 errors
}


I'd suggest that you configure your application to redirect 404 errors to a specific page, such as ~/FourOhFour.aspx. In this page you can inspect the aspxerrorpath querystring parameter, which will report the page the user was attempting to visit. From here you can do all sorts of interesting things, from logging the 404, to emailing yourself a message, to trying to determine the correct URL and auto-redirecting the user to that.

To configure your web application to redirect the user to a custom page in the face of a 404, add the following markup to web.config in the <system.web> section:

<customErrors mode="On" defaultRedirect="~/GeneralError.aspx">
    <error statusCode="404" redirect="~/FourOhFour.aspx" />
</customErrors>

For more information, see:

  • <customErrors> element documentation


You can catch the exception. You're trying to catch this in a client application, correct?

HttpWebRequest req = ( HttpWebRequest )WebRequest.Create( someURL );
try
{
    HttpWebResponse resp = req.GetResponse();
}
catch( WebException webEx )
{
   if( webEx.Response != null )
   {
      HttpWebResponse response = webEx.Response as HttpWebResponse;
      switch( response.StatusCode )
      {
         case HttpStatusCode.NotFound:
             // do something
             break;


In the Web.Config file you can specifiy a seperate File for each error code.

<customErrors mode="Off" defaultRedirect="GenericErrorPage.htm">
        <error statusCode="404" redirect="FileNotFound.aspx" />
    </customErrors>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜