Receiving code 200 when it should be 404

Asked

Viewed 174 times

2

I created an ASP.NET MVC 5 application by adding the following code snippets:

Web.config

<system.web>
  <customErrors mode="On">
    <error statusCode="404" redirect="~/Erro/Erro404"/>
  </customErrors>
</system.web>

Global.asax.Cs

protected void Application_Error(object sender, EventArgs e)
    {
        if (Response.StatusCode != 404) //Condição para ignorar erros 404.
        {
            Exception ex = Server.GetLastError();
            Response.Clear();
            Logger.Registrar(ex.ToString()); //Método que registra o erro em um arquivo de log.
            Server.ClearError();
            Response.Redirect("~/Erro/Desconhecido");
        }
    }

Since I’ve already set an action for 404 errors, I want these to go right through Application_Error, thus leading the user to ~/Erro/Erro404.

The problem: 404 errors always enter the if in Application_Error, because the server returns a status code 200 (OK), when it should be 404 (Not Found).

Can anyone tell where the mistake is?

2 answers

1

Try reversing the verification sequence:

protected void Application_Error(object sender, EventArgs e)
{
   Exception Ex = Server.GetLastError();
   if (Ex != null)
   {
      HttpException httpEx = Ex as HttpException;
      if (httpEx != null && httpEx.GetHttpCode() == 404)
      {
         ... tratamento da 404 ...
      } else {
         Response.Clear();
         Logger.Registrar(ex.ToString());
         Server.ClearError();
         Response.Redirect("~/Erro/Desconhecido");
      }
   }
}
  • I put the Response.TrySkipIisCustomErrors = true; inside Application_Error() and the Response.StatusCode = 404; at the beginning of the view ~/Erro/Erro404. The view now returns 404, but only if it is accessed directly. The rest hasn’t changed a bit. This is how I should do it?

  • When you access an invalid path what happens?

  • received the view with code 200 and the parameter ?aspxerror=/endereco-errado-aqui at the end of the address.

  • IIS 8.0. Is on Azure Websites.

  • @tkpb updated the answer

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.