1

asp.netでエラーが発生しているページURLを取得する方法。
見つからないページの URL が必要なだけです。これは、カスタムエラーの web.config の私のコードです

<customErrors mode="On"  defaultRedirect="ErrorPage.aspx?handler=customErrors%20section%20-%20Web.config">
      <error statusCode="404" redirect="ErrorPage.aspx?msg=404&amp;handler=customErrors%20section%20-%20Web.config"/>
 </customErrors>
4

1 に答える 1

1

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"];
}
于 2013-04-06T12:42:36.803 に答える