Receiving code 200 when it should be 404

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");
        }
    }

As I already set up an action for 404 errors, I want them to pass right through Application_Error , thus leading the user to ~/Erro/Erro404 .

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

Does anyone know where the error is?

    
asked by anonymous 01.05.2014 / 18:39

2 answers

1

To recover the error use so on your Application_Error

protected void Application_Error(object sender, EventArgs e)
{
    var error = Server.GetLastError();
    var code = (error is HttpException) ? (error as HttpException).GetHttpCode() : 500;

    if (code == 404)
    {
        //codificação
    }

}

References:

01.05.2014 / 21:26
1

Try to invert the check 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");
      }
   }
}
    
01.05.2014 / 18:48