我尝试了以下2件事使页面返回404错误:
public ActionResult Index()
{
return new HttpStatusCodeResult(404);
}
public ActionResult NotFound()
{
return HttpNotFound();
}
但它们都只是呈现空白页。如何在ASP.NET MVC 3中手动返回404错误?
最佳答案
如果您使用 fiddler 检查响应,我相信您会发现空白页面实际上返回了404状态代码。问题是没有渲染 View ,因此空白页。
您可以通过向Web.config中添加customErrors元素来获取显示的实际 View ,该元素将在出现特定状态代码时将用户重定向到特定的url,然后您可以像处理任何url一样进行处理。这是下面的演练:
首先在适当的地方扔HttpException。实例化异常时,请确保使用如下重载之一,该重载采用http状态代码作为参数,如下所示。
throw new HttpException(404, "NotFound");
然后在web.config文件中添加一个自定义错误处理程序,以便您可以确定在发生上述异常时应呈现哪种 View 。下面是一个示例:
<configuration>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/404"/>
</customErrors>
</system.web>
</configuration>
现在,在Global.asax中添加一个处理URL的路由条目“404”,它将请求传递给 Controller 的操作,该操作将显示404页面的 View 。
Global.asax
routes.MapRoute(
"404",
"404",
new { controller = "Commons", action = "HttpStatus404" }
);
CommonsController
public ActionResult HttpStatus404()
{
return View();
}
剩下的就是为上述操作添加 View 。
使用上述方法的一个警告:根据《 C#2010中的Pro ASP.NET 4》(Apress)一书,如果使用IIS 7,则customErrors的使用已过时。相反,应使用httpErrors部分。这是这本书的引文:
But although this setting still works with Visual Studio’s built-in test web server, it’s effectively been replaced by the
<httpErrors>
section in IIS 7.x.
关于asp.net-mvc-3 - 返回404错误ASP.NET MVC 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635114/