在ASP.NET中如何识别/处理404异常?

Ale*_*vik 6 asp.net exception-handling http-status-code-404

我需要以不同于其他所有类型的方式处理404异常.识别这些404异常的最佳方法是什么(将它们与其他异常区分开来)?

问题是404错误没有特殊的异常类,我得到常规的System.Web.HttpException,其中Message ="文件不存在".

我应该只使用异常消息还是有更好的方法?

谢谢.

pat*_*ech 18

您可以尝试将异常强制转换为HttpException,然后使用该GetHttpCode方法检查它是否为404.

例如:

Exception ex = Server.GetLastError();

HttpException httpEx = ex as HttpException;

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