1

現在、web.config に次のような customError ノードがあります。

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.aspx">
    <error statusCode="404" redirect="~/themes/generic/common/error-notfound.aspx"/>
</customErrors>

実行時に、redirectMode 属性が ResponseRewrite ではなく ResponseRedirect に設定されているかのようにアプリケーションの動作を変更できるようにしたいと考えています。web.config ファイルを変更せずにこれを実行できる必要があります。これは可能ですか?よろしくお願いします。

4

1 に答える 1

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()
    {
    }
}
于 2012-11-30T18:37:19.013 に答える