mvc 路由 使用
url 特性路由: 特性路由可以在 controller和action里面自定义路由规则 这种方式比较灵活 缺点就是不能很好的统一管理url
注册特性路由:
1 public static void RegisterRoutes(RouteCollection routes) 2 { 3 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 4 5 routes.MapMvcAttributeRoutes();//注册特性路由 6 7 routes.MapRoute( 8 name: "Default", 9 url: "{controller}/{action}/{id}", 10 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 11 ); 12 } 13 //在控制器上使用路由特性 action里面就可以省略 controller 14 [RoutePrefix("home")] 15 public class HomeController : Controller 16 { 17 public ActionResult Index() 18 { 19 return View(); 20 } 21 //特性路由 22 //url http://localhost:17749/home/order/2 23 //page 数据格式验证 24 [Route("home/order/{page:int}")] 25 public ActionResult OrderList(int page) 26 { 27 ViewBag.PageIndex = page; 28 return View(); 29 }
2.传统路由 传统路由可以集中配置路由规则,程序以后的维护比较方便
1 public static void RegisterRoutes(RouteCollection routes) 2 { 3 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 4 5 routes.MapMvcAttributeRoutes();//注册特性路由 6 //自定义名称 必须在默认路由之前 7 routes.MapRoute( 8 "Order", 9 "order/{id}", 10 new { controller = "Order", action = "Details", id = UrlParameter.Optional }, 11 new { id = @"\d" } 12 ); 13 14 routes.MapRoute( 15 name: "Default", 16 url: "{controller}/{action}/{id}", 17 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 18 ); 19 20 } 21 22 23 24 [RoutePrefix("order")] 25 public class OrderController : Controller 26 { 27 //特性路由 28 [Route("")] 29 [Route("list/{page:int?}")] 30 public ActionResult Index(int page = 1) 31 { 32 ViewBag.PageIndex = page; 33 return View(); 34 } 35 //传统路由 36 public ActionResult Details(int id) 37 { 38 ViewBag.Id = id; 39 return View(); 40 } 41 }
<a href="@Url.RouteUrl("Order",new { id = 1 })" target="_blank">Order Details 1</a>
<a href="@Url.RouteUrl("Order",new { id = 2 })" target="_blank">Order Details 2</a>