Asp.net 如何在运行时更改web.config设置的customError配置?
我当前在web.config中有一个customError节点,如下所示:Asp.net 如何在运行时更改web.config设置的customError配置?,asp.net,web-config,custom-error-pages,custom-error-handling,Asp.net,Web Config,Custom Error Pages,Custom Error Handling,我当前在web.config中有一个customError节点,如下所示: <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.aspx"> <error statusCode="404" redirect="~/themes/generic/common/error-notfound.aspx"/> </customErrors> 在运行时,
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.aspx">
<error statusCode="404" redirect="~/themes/generic/common/error-notfound.aspx"/>
</customErrors>
在运行时,我希望能够更改应用程序的行为,使其表现为属性redirectMode被设置为ResponseDirect而不是ResponseWrite。我必须能够在不更改web.config文件的情况下执行此操作。这可能吗?如果可能,如何实现?提前感谢您的帮助 我找到了答案。
在IHTTP模块内,为错误HttpApplicationEvent附加事件处理程序。仅当web.config的customErrors部分设置为ResponseWrite时,才会触发此事件处理程序。事件处理程序在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()
{
}
}