在我的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结尾的网址,会发生重定向,并删除网址的查询字符串。如果我将标签“customErrors”中的参数“redirectMode”更改为“ResponseRewrite”,它将停止为.aspx网址工作,我只是获取默认的ASP.NET错误页面。我怎样才能解决这个问题?我需要404页面上的查询字符串才能将用户重定向到正确的新URL。
/尤
答案 0 :(得分: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;
}
}
}
适合我:)
/尤