如何在没有重定向的情况下在ASP.NET中显示自定义404页面?

当IIS 7上的ASP.NET中的请求为404时,我希望显示自定义错误页面。 地址栏中的URL不应更改,因此不会重定向。 我怎样才能做到这一点?

在应用程序的OnError事件中,您可以测试状态代码为404的HttpExceptions,然后执行Server.Transfer到您的自定义404页面,而不是Response.Redirect。 看看http://blog.dmbcllc.com/2009/03/02/aspnet-application_error-detecting-404s/

作为一般的ASP.NET解决方案,在web.config的customErrors部分中,添加redirectMode =“ResponseRewrite”属性。

   

注意:这在内部使用Server.Transfer(),因此重定向必须是Web服务器上的实际文件。 它不能是MVC路线。

我使用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中启用,与任何其他模块相同

  ...  ...  

您可以使用

 Server.Transfer("404error.aspx")