您可以创建一个 HttpModule 来捕获所有错误,并且比查找导致 404 的 url 做更多的事情。您还可以捕获 500 个错误并做任何您想做的事情。
public class ErrorModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.Error += context_Error;
}
void context_Error(object sender, EventArgs e)
{
var error = HttpContext.Current.Server.GetLastError() as HttpException;
if (error.GetHttpCode() == 404)
{
//use web.config to find where we need to redirect
var config = (CustomErrorsSection) WebConfigurationManager.GetSection("system.web/customErrors");
context.Response.StatusCode = 404;
string requestedUrl = HttpContext.Current.Request.RawUrl;
string urlToRedirectTo = config.Errors["404"].Redirect;
HttpContext.Current.Server.Transfer(urlToRedirectTo + "&errorPath=" + requestedUrl);
}
}
}
现在您需要在 web.config 文件的 httpModules 部分注册它:
<httpmodules>
…
<add name="ErrorModule" type="ErrorModule, App_Code"/>
</httpmodules>
在你的ErrorPage.aspx
你可以从查询字符串中获取 url:
protected void Page_Load(object sender, EventArgs e)
{
string url = Request["errorPath"];
}