![](/img/trans.png)
[英]How redirect all page extensions to custom 404 not found page in an asp.net project?
[英]How to show a custom 404 page in ASP.NET without redirect?
当一个请求是404在IIS 7上的ASP.NET中时,我希望显示一个自定义错误页面。 地址栏中的URL不应更改,因此不能重定向。 我怎样才能做到这一点?
作为常规的ASP.NET解决方案,在web.config的customErrors部分中,添加redirectMode =“ ResponseRewrite”属性。
<customErrors mode="On" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="/404.aspx" />
</customErrors>
注意:这在内部使用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中启用
<httpModules>
...
<add name="CustomErrorsTransferModule" type="WebSite.CustomErrorsTransferModule, WebSite" />
...
</httpModules>
您可以使用
Server.Transfer("404error.aspx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.