【发布时间】:2010-11-24 23:05:43
【问题描述】:
当 IIS 7 上的 ASP.NET 中的请求为 404 时,我希望显示自定义错误页面。地址栏中的 URL 不应更改,因此无需重定向。我该怎么做?
【问题讨论】:
-
你有很多标签 - 这是网络表单还是 MVC?
标签: c# .net asp.net asp.net-mvc vb.net
当 IIS 7 上的 ASP.NET 中的请求为 404 时,我希望显示自定义错误页面。地址栏中的 URL 不应更改,因此无需重定向。我该怎么做?
【问题讨论】:
标签: c# .net asp.net asp.net-mvc vb.net
你可以使用
Server.Transfer("404error.aspx")
【讨论】:
我使用 http 模块来处理这个问题。它适用于其他类型的错误,而不仅仅是 404,并允许您继续使用自定义错误 web.config 部分来配置显示哪个页面。
public class CustomErrorsTransferModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.Error += Application_Error;
}
public void Dispose() { }
private void Application_Error(object sender, EventArgs e)
{
var error = Server.GetLastError();
var httpException = error as HttpException;
if (httpException == null)
return;
var section = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;
if (section == null)
return;
if (!AreCustomErrorsEnabledForCurrentRequest(section))
return;
var statusCode = httpException.GetHttpCode();
var customError = section.Errors[statusCode.ToString()];
Response.Clear();
Response.StatusCode = statusCode;
if (customError != null)
Server.Transfer(customError.Redirect);
else if (!string.IsNullOrEmpty(section.DefaultRedirect))
Server.Transfer(section.DefaultRedirect);
}
private bool AreCustomErrorsEnabledForCurrentRequest(CustomErrorsSection section)
{
return section.Mode == CustomErrorsMode.On ||
(section.Mode == CustomErrorsMode.RemoteOnly && !Context.Request.IsLocal);
}
private HttpResponse Response
{
get { return Context.Response; }
}
private HttpServerUtility Server
{
get { return Context.Server; }
}
private HttpContext Context
{
get { return HttpContext.Current; }
}
}
以与任何其他模块相同的方式在您的 web.config 中启用
<httpModules>
...
<add name="CustomErrorsTransferModule" type="WebSite.CustomErrorsTransferModule, WebSite" />
...
</httpModules>
【讨论】:
作为通用的 ASP.NET 解决方案,在 web.config 的 customErrors 部分中,添加 redirectMode="ResponseRewrite" 属性。
<customErrors mode="On" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="/404.aspx" />
</customErrors>
注意:这在内部使用 Server.Transfer(),因此重定向必须是网络服务器上的实际文件。不能是 MVC 路由。
【讨论】: