public class BookController : Controller
{
public ActionResult Show(int bid)
{
return View();
}
}
routes.MapRoute(
name: "Show",
url: "Book/{bid}/",
defaults: new {controller = "Book", action = "Show"},
constraints: new {bid = @"\d+"}
);
如果访问
/书/测试/
它会返回500错误,如何返回404错误?
如果路由器不匹配,如何返回404?
答案 0 :(得分:0)
您可以通过向web.config添加customErrors元素来显示实际视图,该元素会在发生某个状态代码时将用户重定向到特定网址,然后您可以像处理任何网址一样处理该状态代码。这是以下的演练:
首先抛出适用的HttpException。在实例化异常时,请务必使用其中一个重载,它将http状态代码作为参数,如下所示。
throw new HttpException(404, "NotFound");
然后在web.config文件中添加自定义错误处理程序,以便您可以确定在发生上述异常时应呈现的视图。以下是一个例子:
<configuration>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/404"/>
</customErrors>
</system.web>
</configuration>
现在在Global.asax中添加一个路由条目,用于处理网址&#34; 404&#34;它会将请求传递给控制器的操作,该操作会显示404页面的视图。
Global.asax中
routes.MapRoute(
"404",
"404",
new { controller = "Commons", action = "HttpStatus404" }
);
CommonsController
public ActionResult HttpStatus404()
{
return View();
}
剩下的就是为上面的操作添加一个视图。