1

我目前在我的 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 文件的情况下执行此操作。这可能吗,如果可以,怎么办?预先感谢您的任何帮助。

4

1 回答 1

0

我找到了答案。在 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()
    {
    }
}
于 2012-11-30T18:37:19.013 回答