[翻译:ASP.NET MVC 教程]创建路由约束

赶集要发http://www.ganji18.com

你使用路由约束来使浏览器请求限制在匹配特定路由的中。你可以使用一个正则表达式来具体化一个路由约束。

例如,设想你已在Global.asax文件中定义了清单1中的路由。

清单1——Global.asax.cs

routes.MapRoute( "Product", "Product/{productId}", new {controller="Product", action="Details"} );

清单1包含了一个名为Product的路由。你可以使用Product路由来将浏览器请求映射至清单2中的ProductController控制器中。

清单2——Controllers\ProductController.cs

using System.Web.Mvc; namespace MvcApplication1.Controllers { public class ProductController : Controller { public ActionResult Details(int productId) { return View(); } } }

注意到由Product控制器所表示的Details()动作接受一个名为productId的单一参数。该参数为一整型参数。

定义于清单1中的路由将匹配任何下列的URLs:

· /Product/23

· /Product/7

不幸的是,该路由也将匹配下列URLs:

· /Product/blah

· /Product/apple

因为Detail()动作期待一个整型参数,做一个包含整型值以外的其它类型值的请求将导致一个错误。例如,如果你键入URL /Product/apple到你的浏览器中,那么你将得到如图1所示的错误页面。

clip_image002

图1:出错页面

你真正想做的是仅匹配包含一个合适的整型productId。当定义一个路由来限制匹配该路由的URLs时,你可以使用一个约束。在清单3中被修改过的Product路由包含了一个只匹配整型的正则表达式约束。

清单3——Global.asax.cs

routes.MapRoute( "Product", "Product/{productId}", new {controller="Product", action="Details"}, new {productId = @"\d+" } );

正则表达式\d+匹配一个或更多个整型数字。该约束使Product路由匹配下列URLs:

· /Product/3

· /Product/8999

而不是下列的URLs:

· /Product/apple

· /Product

这些浏览器请求将会被另一个路由处理,要不然如果没有匹配的路由,一个The resource could not be found的错误就会被返回。

posted on 2014-06-06 11:31  chennie  阅读(581)  评论(0编辑  收藏  举报