1

在我的 web.config 文件中使用以下配置,

<customErrors mode="On" redirectMode="ResponseRedirect" >
    <error statusCode="404" redirect="/404" />
</customErrors>   
<httpErrors errorMode="Custom">
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="404" prefixLanguageFilePath="" path="/404" responseMode="ExecuteURL" />
</httpErrors>

404 页面效果很好,但是对于以 .aspx 结尾的 url,会发生重定向,并且会删除该 url 的查询字符串。如果我将标记“customErrors”中的参数“redirectMode”更改为“ResponseRewrite”,它将停止对 .aspx url 工作,我只会得到默认的 ASP.NET 错误页面。我怎样才能解决这个问题?我需要 404 页面上的查询字符串才能将用户重定向到正确的新 url。

/维克托

4

1 回答 1

0

好的,最终为此编写了我自己的http模块,

    public class FileNotFoundModule : IHttpModule
{
    private static CustomErrorsSection _configurationSection = null;
    private const string RedirectUrlFormat = "{0}?404;{1}";

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.Error += new EventHandler(FileNotFound_Error);
    }

    private void FileNotFound_Error(object sender, EventArgs e)
    {
        var context = HttpContext.Current;
        if (context != null && context.Error != null)
        {
            var error = context.Error.GetBaseException() as HttpException;
            if (error != null && error.GetHttpCode() == 404 &&
                (ConfigurationSecion.Mode == CustomErrorsMode.On || (!context.Request.IsLocal && ConfigurationSecion.Mode == CustomErrorsMode.RemoteOnly)) &&
                !string.IsNullOrEmpty(RedirectUrl) && !IsRedirectLoop)
            {
                context.ClearError();
                context.Server.TransferRequest(string.Format(FileNotFoundModule.RedirectUrlFormat, RedirectUrl, context.Request.Url));
            }
        }
    }

    private bool IsRedirectLoop
    {
        get
        {
            var checkUrl = string.Format(FileNotFoundModule.RedirectUrlFormat,RedirectUrl,string.Empty);
            return HttpContext.Current.Request.Url.ToString().Contains(checkUrl);
        }
    }

    private CustomErrorsSection ConfigurationSecion
    {
        get
        {
            if (_configurationSection == null)
            {
                _configurationSection = (CustomErrorsSection)WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath).GetSection("system.web/customErrors");
            }
            return _configurationSection;
        }
    }

    private string RedirectUrl
    {
        get
        {
            foreach (CustomError error in ConfigurationSecion.Errors)
            {
                if (error.StatusCode == 404)
                {
                    return error.Redirect;
                }
            }
            return string.Empty;
        }
    }
}

为我工作:)

/维克托

于 2012-09-19T13:16:47.900 回答