在ASP.NET中
重写URL:
创建一个web项目,内容如下:
???public class RouteConfig ???{ ???????public static void RegisterRoutes(RouteCollection routes) { ???????????routes.MapPageRoute("default","","~/Default.aspx"); ???????????routes.MapPageRoute("cart1","cart","~/Store/Cart.aspx"); ???????????routes.MapPageRoute("cart2","apps/shopping/finish","~/Store/Cart.aspx"); ???????} ???}
MapPageRoute方法有多个重载,最常用的就是给定3个参数。
参数1:路由的名称。
参数2:应用程序支持的新的虚拟路径。(http://localhost:60923/apps/shopping/finish 和 http://localhost:60923/cart 都会指向Cart.aspx这个页面)
参数3:新的虚拟路径所指向的窗体
下面是Global.asax文件中的代码
protected void Application_Start(object sender, EventArgs e) ???????{ ???????????RouteConfig.RegisterRoutes(RouteTable.Routes); ???????}
ASP.NET MVC中
当mvc程序启动的时候会主动调用Global.asax文件中的Application_Start方法,在该方法中又会主动调用静态方法RouteConfig.RegisterRoutes,这个时候会将URL和路由规则逐一进行匹配。
//使用routes.MapRoute 方法注册路由routes.MapRoute("MyRoute", "{controller}/{action}");//创建默认的路由规则routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });//使用静态变量的 Url片段(匹配:http://localhost:20234/xxx/Home/Index)routes.MapRoute("", "xxx/{controller}/{action}", new { controller = "Home", action = "Index" });//使用静态片段和默认值为特定的路由创建别名routes.MapRoute("ShopSchema", "shop/{action}", new { controller = "Home"});//这里用户在url中输入shop,然后会被替换成Home。routes.MapRoute("ShopSchema", "oldController/oldAction", new { controller = "Home",action="Index"});//在控制器的方法中,接收Url中的参数public ActionReulst CustomVariable(){ViewBag.variable=RouteData.Values["id"];//获取Url中,id片段的值return View();}
//约束路由//1、使用正则表达式约束路由,和使用指定的值来约束路由(controller以H打头(正则表达式),action只能是Index或者是About(指定的值))routes.MapRoute("ShopSchema", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home",action="Index",id=UrlParameter.Optional},new {controller="^H.*",action="^Index$|^About$"},new []{"URLsAndRoutes.Controllers"});//2使用HTTP方法约束路由。(好像用的不是太多)controller以H打头(正则表达式),action只能是Index或者是About(指定的值))routes.MapRoute("ShopSchema", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home",action="Index",id=UrlParameter.Optional},new {controller="^H.*",action="Index|About",httpMethod=new HttpMethodConstraint("GET")},new []{"URLsAndRoutes.Controllers"});还有 使用类型约束, 值类型约束 自定义约束。
URL路由
原文地址:https://www.cnblogs.com/vichin/p/9898745.html