.net下返回404错误页面并跳转的解决办法
时间:2010-12-03 来源:蛤蟆
使用web.config中的customErrors来做的话并不好,因为asp.net会在返回的head头上加上302状态,即使你在自定义的404页面上设置Response.StatusCode = 404也是无法消除asp.net加的302错误。因此我的办法就是在全局错误处理Application_Error中设置并返回html代码。
这是代码:

/// <summary>
/// 全局错误处理,记录文件型日志
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
{
Response.Clear();
Response.StatusCode = 404;
Response.Write("<html xmlns=\"http://www.w3.org/1999/xhtml/" ><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>页面没有找到</title><meta http-equiv=\"refresh\" CONTENT=\"0; url=/\"></head><body><div>" +
"<div style=\"display:none;\">页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到页面没有找到</div></div></body></html>");
Response.End();
}
为什么要加那么多的“页面没有找到”呢?是因为ie有个BUG:如果404页面大小不够521b的话会被ie的默认内容替换。
另个需要注意的是meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />这个必须在title标签前,否则ie6下不能跳转。
排行榜 更多 +