程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> ASP.NET設置404頁面返回302HTTP狀態碼的解決方法

ASP.NET設置404頁面返回302HTTP狀態碼的解決方法

編輯:ASP.NET基礎
在配置文件中配置404頁面如下:
復制代碼 代碼如下:
<customErrors mode="On" defaultRedirect="404.aspx">
<error statusCode="403" redirect="404.aspx" />
<error statusCode="404" redirect="404.aspx" />
<error statusCode="400" redirect="404.aspx" />
</customErrors>

訪問網站時錯誤頁面可正常顯示,但HTTP狀態碼卻是302,對SEO很不友好,按下列步驟修改使錯誤頁面返回正確的利於SEO的404狀態碼:

1、在404.aspx中加入代碼:
Response.Status = "404 Moved Permanently";
如果你沒有做偽靜態,或者沒加腳本映射,以上完全沒有問題,不必往下看了。如果做了偽靜態,那麼404頁面返回的狀態碼仍然為302,請看第二步。

2、在 Global.asax 中加入下面的代碼:
復制代碼 代碼如下:
protected void Application_Error(object sender, EventArgs e)
{
//在出現未處理的錯誤時運行的代碼
this.FileNotFound_Error();
}
/// <summary>
/// 404錯誤處理
/// </summary>
private void FileNotFound_Error()
{
HttpException erroy = Server.GetLastError() as HttpException;
if (erroy != null && erroy.GetHttpCode() == 404)
{
Server.ClearError();
string path = "~/404.aspx";
Server.Transfer(path);
//Context.Handler = PageParser.GetCompiledPageInstance(path, Server.MapPath(path), Context);
}
}

至此,這個頑固的問題得以解決。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved