代码之家  ›  专栏  ›  技术社区  ›  Paul Hiles

如何让MVC动作返回404

  •  128
  • Paul Hiles  · 技术社区  · 15 年前

    我有一个操作,它接受一个用于检索某些数据的字符串。如果这个字符串没有返回任何数据(可能是因为它已经被删除了),我想返回404并显示一个错误页面。

    我目前只使用返回一个特殊视图,它显示一个特定于此操作的友好错误消息,表示找不到该项。这样做很好,但理想情况下希望返回404状态代码,以便搜索引擎知道此内容已不存在,并可以将其从搜索结果中删除。

    最好的方法是什么?

    它是否与设置response.statuscode=404一样简单?

    12 回复  |  直到 8 年前
        1
  •  100
  •   Christian Gollhardt    10 年前

    有多种方法可以做到,

    1. 你是对的,在普通的ASPX代码中,它可以用你指定的方式分配。
    2. throw new HttpException(404, "Some description");
        2
  •  141
  •   Christian Gollhardt    10 年前

    在ASP.NET MVC 3及更高版本中,可以返回 HttpNotFoundResult 来自控制器。

    return new HttpNotFoundResult("optional description");
    
        3
  •  55
  •   iCollect.it Ltd    12 年前

    在MVC 4及更高版本中,您可以使用内置的 HttpNotFound 辅助方法:

    if (notWhatIExpected)
    {
        return HttpNotFound();
    }
    

    if (notWhatIExpected)
    {
        return HttpNotFound("I did not find message goes here");
    }
    
        4
  •  24
  •   T.Rob    13 年前

    代码:

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

    Web.CONFIG

    <customErrors mode="On">
      <error statusCode="404" redirect="/Home/NotFound" />
    </customErrors>
    
        5
  •  10
  •   Wout    14 年前

    我用过这个:

    Response.StatusCode = 404;
    return null;
    
        6
  •  5
  •   cem    15 年前

    在Nerddinner,例如,尝试 it

    public ActionResult Details(int? id) {
        if (id == null) {
            return new FileNotFoundResult { Message = "No Dinner found due to invalid dinner id" };
        }
        ...
    }
    
        7
  •  5
  •   Robert Paulsen    9 年前

    如果使用.NET核心,则可以 return NotFound()

        8
  •  4
  •   ganders    10 年前

    在我在下面添加中间一行之前,上面的例子对我都不起作用:

    public ActionResult FourOhFour()
    {
        Response.StatusCode = 404;
        Response.TrySkipIisCustomErrors = true; // this line made it work
        return View();
    }
    
        9
  •  2
  •   bruno    15 年前

    我使用:

    Response.Status = "404 NotFound";
    

    这对我很有用

        10
  •  1
  •   feedthedogs    8 年前

    在.NET核心1.1中:

    return new NotFoundObjectResult(null);
    
        11
  •  0
  •   Christof Mehlstäubler    9 年前

    您还可以执行以下操作:

            if (response.Data.IsPresent == false)
            {
                return StatusCode(HttpStatusCode.NoContent);
            }
    
        12
  •  -1
  •   user4326800    10 年前

    请尝试以下演示代码:

    public ActionResult Test()
    
    {
      return new HttpStatusCodeResult (404,"Not found");
    }