ASP.NET MVC中的404页面

Max*_*sky 5 asp.net iis asp.net-mvc http-status-code-404

我正在构建我的第一个ASP.NET MVC网站,我正在试图弄清楚如何实现404页面.

我应该创建一个名为"404Controller?"的控制器吗?如果是这样,我如何在IIS中注册此控制器,以便将404重定向到该页面?此外,在某些其他控制器代码未找到某些内容(例如,在数据库中)的情况下,如何将请求重定向到我的404页面?

Max*_*oro 14

对于你想要做的事情,没有单一的答案,最简单的和我喜欢的是使用这个HttpException类,例如

public ActionResult ProductDetails(int id) {

   Product p = this.repository.GetProductById(id);

   if (p == null) {
      throw new HttpException(404, "Not Found");
   }

   return View(p);
}
Run Code Online (Sandbox Code Playgroud)

在web.config上,您可以配置customError页面,例如

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
   <error statusCode="404" redirect="Views/Errors/Http404.aspx" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)

  • @David Murdoch:使用`redirectMode ="ResponseRewrite"`没有重定向. (4认同)

Fit*_*aki 7

我最喜欢的选择是返回一个名为404的视图.

if (article == null)
    return View("404");
Run Code Online (Sandbox Code Playgroud)

这将允许您选择在共享文件夹中具有通用404视图,以及具有文章控制器的特定404视图.

此外,一个很大的优点是这里没有重定向.

  • 但这会返回200状态代码,而不是404. (19认同)