3

这是我第一次使用 HttpModules。我需要在现有的 ASP.NET 应用程序中创建一种“拖放”解决方案,通过将用户重定向到新的“ ErrorFeedback.aspx”页面来提供常见的错误处理。因此,当应用程序遇到异常时,用户将被重定向到ErrorFeedback.aspx他们能够在需要时提供有关错误的反馈的位置。我们目前有大约 300 个网络应用程序,因此看起来最有前途的“拖放”解决方案是HttpModule. 此 ErrorFeedback 页面将是一个新页面,也将添加到解决方案中。最终这些组件(DLL 和自定义网页)将在 Nuget 包中结束,但暂时需要手动将其复制/粘贴到现有解决方案中。

我听说在模块内进行重定向是不好的做法。OnError遇到时将用户重定向到特定页面的最佳做法HttpModule是什么?

4

2 回答 2

1

您可以在 Web.config 中使用自定义错误页面,而不是HttpModule. 但是如果你真的需要重定向,最好使用RewitePathmethod

这里有一些一般的注意事项:

  1. 当你使用 URL 重写时,你应该小心 SEO。因为您的原始 URL 将计入 SERP。
  2. ASP.NET 路由也是一种很好的机制,可以替代您尝试做的事情
  3. 为什么你说重定向是不好的HttpModule?有什么具体原因吗?
于 2013-11-14T20:20:20.277 回答
1

如果您只需要重定向,最好使用web.config custom error pages. 但是,如果您还想做一些更多的事情,例如比您需要使用的日志记录,请执行HttpModule以下操作:

public class ErrorManagementModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        //handle context exceptions
        context.Error += (sender, e) => HandleError();
        //handle page exceptions
        context.PostMapRequestHandler += (sender, e) => 
            {
                Page page = HttpContext.Current.Handler as Page;
                if (page != null)
                    page.Error += (_sender, _e) => HandleError();
            };
    }

    private void HandleError()
    {
        Exception ex = HttpContext.Current.Server.GetLastError();
        if (ex == null) return;

        LogException(ex);

        HttpException httpEx = ex as HttpException;
        if (httpEx != null && httpEx.GetHttpCode() == 500)
        {
            HttpContext.Current.Response.Redirect("/PrettyErrorPage.aspx", true);
        }
    }
}
于 2013-11-14T20:43:47.110 回答