Recently, my SEO optimizer told me that he was unhappy with how ASP.NET returns an HTTP response in case of a 404 situation, that is, the page was not found. I started poking around and found a couple of interesting things that might be useful to someone.
1) Usually, by default, so to speak, we catch 404 with these web.config settings
<customErrors defaultRedirect = "GenericError.htm" mode = "On">
<error statusCode = "404" redirect = "404.html" />
')
</ customErrors>
Odanko, this approach has a problem that the SEO optimizer told me about. Let's do a little test and see which HTTP code will be returned to us by ASP.NET in case of a 404 error.

So, we first get 302 (Redirect) and then 200, that is, the type is all good. But this actually turned out to be bad for SEO optimization.
Problem: We need ASP.NET to return HTTP 404 code in the situation when the page is not found, and not just redirect to the error page with code 200.
Solution 1Let's change our web.config a bit and make the redirect not to a static html file but to .aspx
<customErrors defaultRedirect = "GenericError.htm" mode = "On">
<error statusCode = "404" redirect = "404.aspx" />
</ customErrors>
Now add the following code to the Page_Load of this 404.aspx page
protected void Page_Load(object sender, EventArgs e)
{
Response.StatusCode = 404;
}
Now let's test

It looks better, we still received 404 output code, but my CEO optimizer is not satisfied, since we still have a double answer, that is, first 302 redirect code and then 404. This, as I was told, is bad for Google search and we need to return one answer, with 404 code and nothing else.
Solution 2Let's comment out our settings in web.config
<! - <customErrors defaultRedirect = "GenericError.htm" mode = "On">
<error statusCode = "404" redirect = "404.html" />
</ customErrors> ->
Now, add the following code to the global.asax file, or first add this file to our project, if suddenly it is not there. The code logic is to catch the 404 error and redirect to our error information page.
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpException)
{
if (((HttpException)(ex)).GetHttpCode() == 404)
Server.Transfer("~/404.html");
}
//
Server.Transfer("~/GenericError.htm");
}
Ok, now we test

Yahuu, we received our cherished, lonely 404 code for our error from ASP.NET. The CEO optimizer was satisfied, and I, too, spent time with interest :)
Maybe someone will help;)