首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在运行时更改web.config设置的customError配置?

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

Stack Overflow用户
提问于 2012-11-30 10:15:44
回答 1查看 274关注 0票数 1

我目前在web.config中有一个customError节点,如下所示:

代码语言:javascript
复制
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.aspx">
    <error statusCode="404" redirect="~/themes/generic/common/error-notfound.aspx"/>
</customErrors>

在运行时,我希望能够更改应用程序的行为,就像属性redirectMode被设置为ResponseRedirect而不是ResponseRewrite一样。我必须能够在不对web.config文件进行更改的情况下执行此操作。这是可能的吗?如果是的话,是如何实现的?提前感谢您的帮助。

EN

回答 1

Stack Overflow用户

发布于 2012-12-01 02:37:19

我找到了答案。在IHttpModule中,附加错误HttpApplicationEvent的事件处理程序。仅当web.config的customErrors部分设置为ResponseRewrite时,才应触发此事件处理程序。事件处理程序在customError配置之前执行。

代码语言:javascript
复制
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()
    {
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13638074

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档