本文共 2777 字,大约阅读时间需要 9 分钟。
在属性路由中,路由是由直接运用于控制器类的C#属性定义的。在实践中,它可以自由地与标准的基于约定的路由相混合。
默认情况下属性路由是禁用的,通过MapMvcAttributeRoutes扩展方法可以启用它,该扩展方法由RouteCollection对象调用,并且该对象作为参数传递给静态RegisterRoutes方法。
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Mvc.Routing.Constraints;using System.Web.Routing;namespace urlAndRoutes{ public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { //启用属性路由 routes.MapMvcAttributeRoutes(); routes.MapRoute( "Myroute","{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "urlAndRoutes.Controllers" } ); } }}
调用MapMvcAttributeRoutes方法导致路由系统检查应用程序中的控制器类,并寻找配置路由的属性。最重要的属性是Route,下面我们对Customer控制器进行代码修改:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace urlAndRoutes.Controllers{ public class CustomerController : Controller { // GET: Customer [Route("TestCustomerController")]//这是我修改的地方,这样就为index这个动作方法定义了一个静态路由。 public ActionResult Index() { ViewBag.Controller = "Customer"; ViewBag.Action = "Index"; return View("ActionName"); } public ActionResult List() { ViewBag.Controller = "Customer"; ViewBag.Action = "List"; return View("ActionName"); } }}
这样我们就可以这样访问了。
虽然通过属性表示,但属性路支持和基于约定的路由一样的特性。这些特性包括创建包含片段变量的路由。
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace urlAndRoutes.Controllers{ public class CustomerController : Controller { // GET: Customer [Route("Users/add/{user}/{id}")] public string Create(string user,int id) { return string.Format("user:{0},id:{1}",User,id); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace urlAndRoutes.Controllers{ [RoutePrefix("Users")] public class CustomerController : Controller { // GET: Customer [Route("TestCustomerController")] public ActionResult Index() { ViewBag.Controller = "Customer"; ViewBag.Action = "Index"; return View("ActionName"); } [Route("~/List")] public ActionResult List() { ViewBag.Controller = "Customer"; ViewBag.Action = "List"; return View("ActionName"); } }}
为此,我们可以用访问啦。
另外,大家应该注意一下:
使用RoutePrefix属性指明动作方法的路由应该以Users为前缀。但是当出现如下模板的时候,不用users做前缀。
[Route("~/List")]
效果图如下:
源码下载: