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"];
}