这是我第一次使用 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/