如何获取pageurl表单在asp.net中发生了哪些错误

时间:2013-04-06 12:08:45

标签: c# asp.net web-config

如何获取asp.net中发生错误的pageurl 我只需要找不到的页面网址。 这是我的自定义错误的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>

1 个答案:

答案 0 :(得分: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中,您可以从查询字符串中获取网址:

protected void Page_Load(object sender, EventArgs e)
{
    string url = Request["errorPath"];
}