2016-08-17 36 views
0
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+"} 
       ); 

如果访问如果路由器不匹配,如何返回404?

/电子书/测试/

它会返回500错误,如何返回404错误?

如果路由器不匹配,如何返回404?

+1

试试这里:http://stackoverflow.com/questions/553922/custom-asp-net-mvc-404-error-page –

回答

0

你可以通过向你的web.config添加一个customErrors元素来显示一个实际的视图,当一个特定的状态代码发生时你将把用户重定向到一个特定的url,然后你可以像处理任何url一样处理。下面是一个步骤:

首先抛出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中的路由条目会处理的URL“404”,这将请求传递给控制器​​的作用是会显示你的404页面查看。

的Global.asax

routes.MapRoute(
    "404", 
    "404", 
    new { controller = "Commons", action = "HttpStatus404" } 
); 

CommonsController

public ActionResult HttpStatus404() 
{ 
    return View(); 
} 

所有剩下的就是添加一个视图上述操作。