我目前在web.config中有一个customError节点,如下所示:
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.aspx">
<error statusCode="404" redirect="~/themes/generic/common/error-notfound.aspx"/>
</customErrors>在运行时,我希望能够更改应用程序的行为,就像属性redirectMode被设置为ResponseRedirect而不是ResponseRewrite一样。我必须能够在不对web.config文件进行更改的情况下执行此操作。这是可能的吗?如果是的话,是如何实现的?提前感谢您的帮助。
发布于 2012-12-01 02:37:19
我找到了答案。在IHttpModule中,附加错误HttpApplicationEvent的事件处理程序。仅当web.config的customErrors部分设置为ResponseRewrite时,才应触发此事件处理程序。事件处理程序在customError配置之前执行。
public class ErrorHandlingHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
// Read web.config
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var systemWebSection = configuration.GetSectionGroup("system.web") as SystemWebSectionGroup;
if (systemWebSection == null ||
systemWebSection.CustomErrors == null ||
systemWebSection.CustomErrors.Mode == CustomErrorsMode.Off ||
systemWebSection.CustomErrors.RedirectMode != CustomErrorsRedirectMode.ResponseRewrite)
{
return;
}
var customErrorsSection = systemWebSection.CustomErrors;
context.Error +=
(sender, e) =>
{
if (customErrorsSection.Mode == CustomErrorsMode.RemoteOnly && context.Request.IsLocal)
{
return;
}
var app = (HttpApplication)sender;
var httpException = app.Context.Error as HttpException;
// Redirect to a specific url for a matching status code
if (httpException != null)
{
var error = customErrorsSection.Errors.Get(httpException.GetHttpCode().ToString("D"));
if (error != null)
{
context.Response.Redirect(error.Redirect);
return;
}
}
// Redirect to the default redirect
context.Response.Redirect(customErrorsSection.DefaultRedirect);
};
}
public void Dispose()
{
}
}https://stackoverflow.com/questions/13638074
复制相似问题