c# - HttpModule - 需要在 OnError 命中时将用户重定向到特定页面

标签 c# asp.net redirect httpmodule ihttpmodule

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

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

最佳答案

如果您只需要重定向,最好使用 web.config 自定义错误页面。 但是如果你还想做更多的事情,比如日志记录,那么你需要使用 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);
        }
    }
}

关于c# - HttpModule - 需要在 OnError 命中时将用户重定向到特定页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19987520/

相关文章:

c# - 说明静态成员

c# - 同一属性的不同 getter 和 setter 接口(interface)

c# - 如何将多个选定的 Datagrid 值传递到 asp.net 中的另一个页面?

ASP.NET sessionState SQLServer模式超时不起作用

apache - 如果找不到内容,则重定向到旧站点

c# - 当设置了 DefaultCellStyle.Format 且数据为空时显示空单元格

c# - 我们如何在 WinRT 应用程序中设置计时器?

javascript - 将 GridView 列值传递给 Javascript 函数 - OnClientClick

url - 登录失败时将用户从 Moodle 重定向到另一个站点

javascript - ng-click 后 AngularJS 重定向