一、路由常规设置
1、URL模式路由系统用一组路由来实现它的功能。这些路由共同组成了应用程序的URL架构或方案。URL的两个关键行为:a.URL模式是保守的,因而只匹配与模式具有相同片段数的URL。b.URL模式是宽松的,如果一个URL正好居右正确的片段数,该模式就会用来为片段变量提取值,而不管这个值可能是什么。2、使用静态URL片段//Controller会加上Xroutes.MapRoute("", "X{controller}/{action}",new { controller = "Product", action = "Index" });//会导航到Store这个控制器中,而不会导航到Product控制器routes.MapRoute("Store", "Store/{action}",new { controller = "Product" });routes.MapRoute("", "{controller}/{action}",new { controller = "Product", action = "Index" });//路由的格式必须是Public/开头routes.MapRoute("", "Public/{controller}/{action}",new { controller = "Product", action = "Index" });3、定义自定义片段变量/*如果在URL中没有{id}这个片段,默认下会把DefaultId赋值给id*/routes.MapRoute("", "{controller}/{action}/{id}",new { controller = "Product", action = "Index" ,id="DefaultId"});4、定义可选URL片段//id默认值是UrlParameter.Optional,表明片段变量是可选的routes.MapRoute("", "{controller}/{action}/{id}",new { controller = "Product", action = "Index" ,id=UrlParameter.Optional);5、定义可变长路由/*改变URL模式默认保守性的另一种方式是接收可变数目的URL片段。通过一个全匹配(catchall)的片段变量,并以星号(*)作为其前缀,便可以定义对可变片段数的支持。*/routes.MapRoute("", "{controller}/{action}/{id}/{*catchall}",new { controller = "", action = "", id = UrlParameter.Optional });6、按命名空间区分控制器优先顺序routes.MapRoute("", "{controller}/{action}/{id}/{*catchall}",new { controller = "", action = "", id = UrlParameter.Optional },/*这句话的作用:让mvc框架首先去AdditionalControllers这个命名空间下找控制器,*如果没找到合适的控制器,mvc框架默认会回到正常行为。*/new[] { "URLsAndRoutes.AdditionalControllers" });禁用备用命名空间Route myRoute = routes.MapRoute("", "{controller}/{action}/{id}/{*catchall}",new { controller = "", action = "", id = UrlParameter.Optional }new[] { "URLsAndRoutes.AdditionalControllers" });/*这句话是指如果AdditionalControllers命名空间下没有相匹配的控制,请求会失败。*/myRoute.DataTokens["UseNamespaceFallback"] = false;
二、约束路由
1、用正则表达式约束路由、将一条路有约束到一组指定的值
Route myRoute = routes.MapRoute("", "{controller}/{action}/{id}/{*catchall}",new { controller = "", action = "", id = UrlParameter.Optional },/*controller = "^H.*" 用正则表达式来约定路由,它只匹配以H开头的控制器;*action只匹配Index或About的URL。*/new { controller = "^H.*", action = "^Index$|^About$" });
2、使用HTTP方法约束路由
routes.MapRoute("", "{controller}/{action}/{id}/{*catchall}",new { controller = "", action = "", id = UrlParameter.Optional },/**httpMethod只允许GET请求。*/new{ httpMethod = new HttpMethodConstraint("GET") },new[] { "URLsAndRoutes.AdditionalControllers" });
3、使用类型和值约束
routes.MapRoute("", "{controller}/{action}/{id}/{*catchall}",new { controller = "", action = "", id = UrlParameter.Optional },/**id是10到20之间的一个数字。*/new{ id= new RangeRouteConstraint(10,20) },new[] { "URLsAndRoutes.AdditionalControllers" });
4、定义自定义约束
public class UserAgentConstraint : IRouteConstraint{private string requiredUserAgent;public UserAgentConstraint(string agentParm){requiredUserAgent = agentParm;}/// <summary>/// 确定 URL 参数是否包含此约束的有效值。/// </summary>/// <param name="httpContext">一个对象,封装有关 HTTP 请求的信息</param>/// <param name="route">此约束所属的对象</param>/// <param name="parameterName">正在检查的参数的名称</param>/// <param name="values">一个包含 URL 的参数的对象</param>/// <param name="routeDirection">一个对象,指示在处理传入请求或生成 URL 时,是否正在执行约束检查</param>/// <returns>如果 URL 参数包含有效值,则为 true;否则为 false</returns>public bool Match(HttpContextBase httpContext, Route route, string parameterName,RouteValueDictionary values, RouteDirection routeDirection){bool flag = false;//判断处理客户端UserAgent属性flag = httpContext.Request.UserAgent != null&& httpContext.Request.UserAgent.Contains(requiredUserAgent);return flag;}}//只匹配来自用户代理字符串含有Chrome的浏览器请求。
routes.MapRoute("", "{*cathcall}",
new { controller = "Product", action = "Index" },
new { customConstraint = new UserAgentConstraint("Chrome") },new[] { "URLsAndRoutes.AdditionalControllers" });
三、使用属性路由
1、启用和运用属性路由
在RegisterRoutes方法中加入这一句:routes.MapMvcAttributeRoutes();这样就可以使用属性路由。例如://[RoutePrefix("Homes")]//前缀,在Url中会加入 Homes 例:http://localhost:11236/Homes/Home/List/11-124public class HomeController : Controller{//// GET: /Home/public ActionResult Index(int id = 8){ViewBag.ControllerName = "Home";ViewBag.ActionName = "Index";return View();}//[Route("Home/List/{id:int}-//{name}")]//http://localhost:11236/Homes/Home/List/11-124
[Route("~/Test")]public ActionResult List(int id = 8){ViewBag.ControllerName = "Home";ViewBag.ActionName = "List";//ViewBag.Id = RouteData.Values["id"];//只能获取到路由中定义的{id}ViewBag.Id = id;return View();}}
默认的mvc路由:
public static void RegisterRoutes(RouteCollection rotues){
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller="Home",action="Index",id=Urlparameter.Optional}
);
}
不带参数的路由:
routes.MapRoute
("NoParameter","{controller}/{action}/{id}");三.带命名空间的路由routes.MapRoute(
"AdminControllers", // 路由名称
"{controller}/{id}-{action}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值
new string[] { "Admin.Controllers" }//命名空间
);四.带约束的路由规则(约束的意思就是用正则这类约束必须符合条件才可以)routes.MapRoute(
"RuleControllers",
"{controller}/{action}-{Year}-{Month}-{Day}}",
new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" },
new { Year = @"^\d{4}", Month = @"\d{2}" } //4位数 2位数
);五.带名称空间,带约束,带默认值的路由规则routes.MapRoute(
"Rule1",
"Admin/{controller}/{action}-{Year}-{Month}-{Day}",
new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" },
new { Year = @"^\d{4}", Month = @"\d{2}" },
new string[] { "Admin.Controllers" }
);六.捕获所有的路由routes.MapRoute(
"All", // 路由名称
"{*Vauler}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
);