SEO 优化之 .Net 2.0 下自定义 404 页面
上一篇介绍了在asp.net下自定义404页面并statuscode是404,有网页提醒那个方法需要.net 3.5及以上的环境,因为redirectMode="ResponseRewrite"
是在asp.net 3.5上新加的。
在asp.net 2.0 下我们可以在全局错误处理Application_Error中实现自定义404页面,并返回statuscode:404。
废话少说,代码如下:
protected void Application_Error(object sender, EventArgs e)
{
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
System.Web.Configuration.CustomErrorsSection customErrors = (System.Web.Configuration.CustomErrorsSection)config.GetSection("system.web/customErrors");
if (customErrors != null && (customErrors.Mode == System.Web.Configuration.CustomErrorsMode.On || customErrors.Mode == System.Web.Configuration.CustomErrorsMode.RemoteOnly))
{
System.Web.HttpApplication app = (HttpApplication)sender;
System.Exception lastError = app.Server.GetLastError();
System.Web.HttpException httpEx = (HttpException)lastError;
if (httpEx != null)
{
int httpErrorCode = httpEx.GetHttpCode();
string redirect = customErrors.DefaultRedirect;
foreach (System.Web.Configuration.CustomError error in customErrors.Errors)
{
if (error.StatusCode == httpErrorCode) redirect = error.Redirect;
}
app.Server.ClearError();
app.Context.Response.StatusCode = httpErrorCode;
Server.Transfer(redirect);
}
}
}
不过,有一点需要注意一下,在IE和Chrome下,小于512b的自定义错误页面默认会被浏览器自带的错误页面替换掉的:)
0 comments:
Post a Comment