一、上面是路由定义的规则,id表示如果没有参数默认id=defaultid
在后台获取的方法:RouteData.Values["id"]
或者直接写到参数里面如下:
public ActionResult CustomVariable(string id)
{
ViewBag.Controller = "Home";
ViewBag.Action = "CustomVariable";
//ViewBag.Custom = RouteData.Values["id"];
ViewBag.Custom = id;
return View();
}
二、参数可选定义id类型即可id = UrlParameter.Optional
routes.MapRoute(
"MyRout",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
三、定义默认参数 使接收的参数总有一个值
public ActionResult CustomVariable(string id="DefaultId")
routes.MapRoute(
"MyRout",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
*catchall 代表了后面可以是任意长度的地址,http://www.aaa.com/Home/Index/123/ss/tt 将不会报错。五、按命名空间区分控制器优先顺序
在实际项目中如果有两个控制器重名,mvc将会报错,为了解决这一问题可以指定控制器命名空间来明确。
routes.MapRoute(
"MyRout",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MvcRoute.NewControllers"}
);
---------------路由约束------------
一、用正则表达式来约束路由
routes.MapRoute(
"MyRout",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new{controller="^H.*"},
new[] { "MvcRoute.NewControllers"}
);
上述表示匹配controller以H字母开头的url二、将一条路由约束到一组指定的值(表示只对action=Index或About起作用)
routes.MapRoute(
"MyRout",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new{controller="^H.*",action="^Index$|^About$"},
new[] { "MvcRoute.NewControllers"}
);
三、使用HTTP方法约束路由 HttpMethod= new HttpMethodConstraint("GET")
routes.MapRoute(
"MyRout",
"{controller}/{action}/{id}/{*catchall}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new{controller="^H.*",action="^Index$|^About$",HttpMethod= new HttpMethodConstraint("GET")},
new[] { "MvcRoute.NewControllers"}
);
也可这样写:httpMethod= new HttpMethodConstraint("GET","POST")四、自定义约束
新建一个类继承IRouteConstraint接口
public class UserAgentConstraint:IRouteConstraint
{
private string requiredUserAgent;
public UserAgentConstraint(string agentParam)
{
requiredUserAgent = agentParam;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return httpContext.Request.UserAgent != null && httpContext.Request.UserAgent.Contains(requiredUserAgent);
}
}
添加新的路由规则
routes.MapRoute(
"ChromeRoute",
"{*catchall}",
new { controller = "Home", action = "Index"},
new { customConstraint=new UserAgentConstraint("Chrome")}
);
五、对磁盘文件的请求进行路由
1、新建一个html文件,并导航到其地址,路由可以正确找打html页面,这说明路由会先考察一个url是否匹配磁盘文件,因此不必添加一个路由即可找到该html页面。
如果不想让mvc框架先考察磁盘文件只需在定义路由的最上面加一句话即可逆转这种行为:
routes.RouteExistingFiles = true;
另外还要在IISExpress里进行配置一下,找到iis站点下的Config 查找UrlRoutingModule-4.0 设置 preCondition=""
2、为磁盘文件定义路由
routes.MapRoute(
"DiskFile",
"Content/staticContent.html",
new { controller = "Customer", action = "List" }
);