Cómo obtener acción MVC para devolver 404


Tengo una acción que toma una cadena que se utiliza para recuperar algunos datos. Si esta cadena resulta en que no se devuelvan datos (tal vez porque se ha eliminado), quiero devolver un 404 y mostrar una página de error.

Actualmente solo uso devolver una vista especial que muestra un mensaje de error amigable específico para esta acción diciendo que el elemento no se encontró. Esto funciona bien, pero lo ideal sería devolver un código de estado 404 para que los motores de búsqueda sepan que este contenido ya no existe y puede eliminarlo de los resultados de búsqueda.

¿Cuál es la mejor manera de hacerlo?

Es tan simple como configurar la respuesta.Código de estado = 404?

Author: Paul Hiles, 2010-06-01

12 answers

Hay múltiples maneras de hacerlo,

  1. Tiene razón en el código aspx común, se puede asignar de la manera especificada
  2. throw new HttpException(404, "Some description");
 95
Author: Dewfy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-29 20:33:42

En ASP.NET MVC 3 y superior puede devolver un HttpNotFoundResult desde el controlador.

return new HttpNotFoundResult("optional description");
 138
Author: Stefan Paul Noack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-29 20:30:11

En MVC 4 y superiores puede usar los métodos auxiliares incorporados HttpNotFound:

if (notWhatIExpected)
{
    return HttpNotFound();
}

O

if (notWhatIExpected)
{
    return HttpNotFound("I did not find message goes here");
}
 53
Author: Gone Coding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-10 10:37:13

Código :

if (id == null)
{
  throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
}

Web.config

<customErrors mode="On">
  <error statusCode="404" redirect="/Home/NotFound" />
</customErrors>
 24
Author: Sinan BARAN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-18 17:52:34

He usado esto:

Response.StatusCode = 404;
return null;
 9
Author: Wout,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-19 21:46:20

En NerdDinner eg. Try it

public ActionResult Details(int? id) {
    if (id == null) {
        return new FileNotFoundResult { Message = "No Dinner found due to invalid dinner id" };
    }
    ...
}
 5
Author: cem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-01 12:40:52

Si está trabajando con. NET Core, puede return NotFound()

 5
Author: Robert Paulsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-13 21:04:19

Ninguno de los ejemplos anteriores funcionó para mí hasta que agregué la línea central a continuación:

public ActionResult FourOhFour()
{
    Response.StatusCode = 404;
    Response.TrySkipIisCustomErrors = true; // this line made it work
    return View();
}
 4
Author: ganders,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-25 05:48:30

Utilizo:

Response.Status = "404 NotFound";

Esto funciona para mí: -)

 2
Author: bruno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-01 09:26:33

En. NET Core 1.1:

return new NotFoundObjectResult(null);
 1
Author: feedthedogs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-16 11:04:59

También puedes hacer:

        if (response.Data.IsPresent == false)
        {
            return StatusCode(HttpStatusCode.NoContent);
        }
 0
Author: Christof Mehlstäubler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-11 15:07:30

Por favor, intente el siguiente código de demostración:

public ActionResult Test()

{
  return new HttpStatusCodeResult (404,"Not found");
}
 -1
Author: user4326800,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-05 00:41:04