我正在构建我的第一个 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/