ASP. NET set 404 page to return 302HTTP status code solution

  • 2020-06-23 00:08:36
  • OfStack

Configure the 404 page in the configuration file as follows:
 
<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> 

When visiting the website, the error page will display normally, but the HTTP status code is 302, which is not SEO friendly. Follow the following steps to make the error page return the correct SEO 404 status code:

1. Add the code in 404.aspx:
Response.Status = "404 Moved Permanently";
If you don't do pseudo-static, or don't add script mapping, that's fine, don't bother looking. If pseudo-static is done, the 404 page still returns a status code of 302. See Step 2.

2. Add the following code to Global. asax:
 
protected void Application_Error(object sender, EventArgs e) 
{ 
// Code that runs when an unhandled error occurs  
this.FileNotFound_Error(); 
} 
/// <summary> 
/// 404 Error handling  
/// </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); 
} 
} 

So far, the stubborn problem has been solved.

Related articles: