如何在运行时更改web.config设置的customError配置?

时间:2012-11-30 02:15:44

标签: 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>

在运行时期间,我希望能够更改应用程序行为,就像将属性redirectMode设置为ResponseRedirect而不是ResponseRewrite一样。我必须能够在不更改web.config文件的情况下执行此操作。这是可能的,如果是这样的话怎么样?预先感谢您的任何帮助。

1 个答案:

答案 0 :(得分:0)

我找到了答案。 在IHttpModule中,附加Error 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()
    {
    }
}