routes.MapRoute( name: "blog", //包含参数的url url: "{year}-{month}-{day}", defaults: new { Controller = "blog", Action = "index" }, //参数的约束 constraints: new { year = @"d{4}", month = @"d{2}", day = @"d{2}" } //namespaces: new string[]{} ); routes.MapRoute( "Test", //不包含参数的url "i-am-home-page", new { controller = "Home", action = "Index" } );
或自定义route类,一条路由一个类
public class MyRouter : RouteBase { public override RouteData GetRouteData(HttpContextBase httpContext) { //home-index //home-index-123 var virtualPath = httpContext.Request.AppRelativeCurrentExecutionFilePath; virtualPath = virtualPath.Substring(2).Trim(); string[] paths = virtualPath.Split('-'); var data = new RouteData(this, new MvcRouteHandler()); data.Values.Add("controller", paths[0]); data.Values.Add("action", paths[1]); if (paths.Length > 2) { data.Values.Add("id", paths[2]); } return data; } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { if (!values.ContainsKey("controller") || values["controller"].ToString().ToLower() != "home") { return null; } if (!values.ContainsKey("action") || values["action"].ToString().ToLower() != "index") { return null; } var path = values["controller"].ToString() + "-" + values["action"].ToString(); if (!string.IsNullOrEmpty(values["id"].ToString())) { path += "-" + values["id"].ToString(); } return new VirtualPathData(this, path); } }