asp.net - ASP.NET MVC 中的 404 页

标签 asp.net asp.net-mvc iis http-status-code-404

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

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

最佳答案

对于您想要做什么,没有单一的答案,最简单和我喜欢的是使用 HttpException类,例如

public ActionResult ProductDetails(int id) {

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

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

   return View(p);
}

在 web.config 上,您可以配置 customError 页面,例如
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
   <error statusCode="404" redirect="Views/Errors/Http404.aspx" />
</customErrors>

关于asp.net - ASP.NET MVC 中的 404 页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2573662/

相关文章:

javascript - html select 只返回第一个选项

asp.net - ASP.NET 按钮周围的虚线边框

asp.net-mvc - 测试方法中的 Moq Automapper 服务在映射时返回 null

c# - C# 线程初学者

xml - 使用 Web Deploy 3.0 在 IIS 中显示下拉列表

asp.net - 基本的 Mono 安装不起作用

c# - String.Format 一个整数以在丹麦文化中使用带有十进制值的千位分隔符

c# - DropCreateDatabaseAlways 在 EntityFramework Core 中

c# - ASP.NET MVC。如何手动将 "cascade delete"添加到代码优先关系中?

asp.net-mvc - asp.net mvc 路由与 IIS7 中的物理路径冲突