史上最全的ASP.NET MVC路由配置

时间:2023-03-09 00:10:53
史上最全的ASP.NET MVC路由配置

MVC将一个Web应用分解为:Model、View和Controller。ASP.NET MVC框架提供了一个可以代替ASP.NETWebForm的基于MVC设计模式的应用。

AD:51CTO 网+ 第十二期沙龙:大话数据之美_如何用数据驱动用户体验

史上最全的ASP.NET MVC路由配置

XD 首先说URL的构造。 其实这个也谈不上构造,只是语法特性吧。

一、命名参数规范+匿名对象

routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 

构造路由然后添加

  1. Route myRoute = new Route("{controller}/{action}", new MvcRouteHandler());
  2. routes.Add("MyRoute", myRoute);

二、直接方法重载+匿名对象

  1. routes.MapRoute("ShopSchema", "Shop/{action}", new { controller = "Home" });

个人觉得第一种比较易懂,第二种方便调试,第三种写起来比较效率吧。各取所需吧。本文行文偏向于第三种。

1.默认路由(MVC自带)

  1. routes.MapRoute(
  2. "Default", // 路由名称
  3. "{controller}/{action}/{id}", // 带有参数的 URL
  4. new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 (UrlParameter.Optional-可选的意思) );

2.静态URL段

  1. routes.MapRoute("ShopSchema2", "Shop/OldAction", new { controller = "Home", action = "Index" });
  2. routes.MapRoute("ShopSchema", "Shop/{action}", new { controller = "Home" });
  3. routes.MapRoute("ShopSchema2", "Shop/OldAction.js",
  4. new { controller = "Home", action = "Index" });

没有占位符路由就是现成的写死的。

比如这样写然后去访问http://localhost:XXX/Shop/OldAction.js,response也是完全没问题的。 controller , action , area这三个保留字就别设静态变量里面了。

3.自定义常规变量URL段

  1. routes.MapRoute("MyRoute2", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "DefaultId" });

这种情况如果访问 /Home/Index 的话,因为第三段(id)没有值,根据路由规则这个参数会被设为DefaultId

这个用viewbag给title赋值就能很明显看出

  1. ViewBag.Title = RouteData.Values["id"];

结果是标题显示为DefaultId, 注意要在控制器里面赋值,在视图赋值没法编译的。

4.再述默认路由

然后再回到默认路由。 UrlParameter.Optional这个叫可选URL段.路由里没有这个参数的话id为null。 照原文大致说法,这个可选URL段能用来实现一个关注点的分离。刚才在路由里直接设定参数默认值其实不是很好。照我的理解,实际参数是用户发来的,我们做的只是定义形式参数名。但是,如果硬要给参数赋默认值的话,建议用语法糖写到action参数里面。比如:

  1. public ActionResult Index(string id = "abcd"){ViewBag.Title = RouteData.Values["id"];return View();}

5.可变长度路由

  1. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });

在这里id和最后一段都是可变的,所以 /Home/Index/dabdafdaf 等效于 /Home/Index//abcdefdjldfiaeahfoeiho 等效于 /Home/Index/All/Delete/Perm/.....

6.跨命名空间路由

这个提醒一下记得引用命名空间,开启IIS网站不然就是404。这个非常非主流,不建议瞎搞。

  1. routes.MapRoute("MyRoute","{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional },new[] { "URLsAndRoutes.AdditionalControllers", "UrlsAndRoutes.Controllers" });

但是这样写的话数组排名不分先后的,如果有多个匹配的路由会报错。 然后作者提出了一种改进写法。

  1. routes.MapRoute("AddContollerRoute","Home/{action}/{id}/{*catchall}",new { controller = "Home", action = "Index", id = UrlParameter.Optional },new[] { "URLsAndRoutes.AdditionalControllers" });
  2. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}", new { controller = "Home", action = "Index", id = UrlParameter.Optional },new[] { "URLsAndRoutes.Controllers" });

这样第一个URL段不是Home的都交给第二个处理 最后还可以设定这个路由找不到的话就不给后面的路由留后路啦,也就不再往下找啦。

  1. Route myRoute = routes.MapRoute("AddContollerRoute",
  2. "Home/{action}/{id}/{*catchall}",
  3. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  4. new[] { "URLsAndRoutes.AdditionalControllers" });  myRoute.DataTokens["UseNamespaceFallback"] = false;

7.正则表达式匹配路由

  1. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  2. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  3. new { controller = "^H.*"},
  4. new[] { "URLsAndRoutes.Controllers"});

约束多个URL

  1. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  2. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  3. new { controller = "^H.*", action = "^Index$|^About$"},
  4. new[] { "URLsAndRoutes.Controllers"});

8.指定请求方法

  1. routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*catchall}",
  2. new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  3. new { controller = "^H.*", action = "Index|About", httpMethod = new HttpMethodConstraint("GET") },
  4. new[] { "URLsAndRoutes.Controllers" });

9.最后还是不爽的话自己写个类实现 IRouteConstraint的匹配方法。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Routing;
  6. /// <summary>
  7. /// If the standard constraints are not sufficient for your needs, you can define your own custom constraints by implementing the IRouteConstraint interface.
  8. /// </summary>
  9. public class UserAgentConstraint : IRouteConstraint
  10. {
  11. private string requiredUserAgent;
  12. public UserAgentConstraint(string agentParam)
  13. {
  14. requiredUserAgent = agentParam;
  15. }
  16. public bool Match(HttpContextBase httpContext, Route route, string parameterName,
  17. RouteValueDictionary values, RouteDirection routeDirection)
  18. {
  19. return httpContext.Request.UserAgent != null &&
  20. httpContext.Request.UserAgent.Contains(requiredUserAgent);
  21. }
  22. }
  1. routes.MapRoute("ChromeRoute", "{*catchall}",
  2. new { controller = "Home", action = "Index" },
  3. new { customConstraint = new UserAgentConstraint("Chrome") },
  4. new[] { "UrlsAndRoutes.AdditionalControllers" });

比如这个就用来匹配是否是用谷歌浏览器访问网页的。

10.访问本地文档

  1. routes.RouteExistingFiles = true;
  2. routes.MapRoute("DiskFile", "Content/StaticContent.html", new { controller = "Customer", action = "List", });

浏览网站,以开启 IIS Express,然后点显示所有应用程序-点击网站名称-配置(applicationhost.config)-搜索UrlRoutingModule节点

  1. <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="managedHandler,runtimeVersionv4.0" />

把这个节点里的preCondition删除,变成

  1. <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />

11.直接访问本地资源,绕过了路由系统

  1. routes.IgnoreRoute("Content/{filename}.html");

文件名还可以用 {filename}占位符。

IgnoreRoute方法是RouteCollection里面StopRoutingHandler类的一个实例。路由系统通过硬-编码识别这个Handler。如果这个规则匹配的话,后面的规则都无效了。 这也就是默认的路由里面routes.IgnoreRoute("{resource}.axd/{*pathInfo}");写最前面的原因。

三、路由测试(在测试项目的基础上,要装moq)

  1. PM> Install-Package Moq
  1. using System;
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;
  3. using System.Web;
  4. using Moq;
  5. using System.Web.Routing;
  6. using System.Reflection;
  7. [TestClass]
  8. public class RoutesTest
  9. {
  10. private HttpContextBase CreateHttpContext(string targetUrl = null, string HttpMethod = "GET")
  11. {
  12. // create the mock request
  13. Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
  14. mockRequest.Setup(m => m.AppRelativeCurrentExecutionFilePath)
  15. .Returns(targetUrl);
  16. mockRequest.Setup(m => m.HttpMethod).Returns(HttpMethod);
  17. // create the mock response
  18. Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();
  19. mockResponse.Setup(m => m.ApplyAppPathModifier(
  20. It.IsAny<string>())).Returns<string>(s => s);
  21. // create the mock context, using the request and response
  22. Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
  23. mockContext.Setup(m => m.Request).Returns(mockRequest.Object);
  24. mockContext.Setup(m => m.Response).Returns(mockResponse.Object);
  25. // return the mocked context
  26. return mockContext.Object;
  27. }
  28. private void TestRouteMatch(string url, string controller, string action, object routeProperties = null, string httpMethod = "GET")
  29. {
  30. // Arrange
  31. RouteCollection routes = new RouteCollection();
  32. RouteConfig.RegisterRoutes(routes);
  33. // Act - process the route
  34. RouteData result = routes.GetRouteData(CreateHttpContext(url, httpMethod));
  35. // Assert
  36. Assert.IsNotNull(result);
  37. Assert.IsTrue(TestIncomingRouteResult(result, controller, action, routeProperties));
  38. }
  39. private bool TestIncomingRouteResult(RouteData routeResult, string controller, string action, object propertySet = null)
  40. {
  41. Func<object, object, bool> valCompare = (v1, v2) =>
  42. {
  43. return StringComparer.InvariantCultureIgnoreCase
  44. .Compare(v1, v2) == 0;
  45. };
  46. bool result = valCompare(routeResult.Values["controller"], controller)
  47. && valCompare(routeResult.Values["action"], action);
  48. if (propertySet != null)
  49. {
  50. PropertyInfo[] propInfo = propertySet.GetType().GetProperties();
  51. foreach (PropertyInfo pi in propInfo)
  52. {
  53. if (!(routeResult.Values.ContainsKey(pi.Name)
  54. && valCompare(routeResult.Values[pi.Name],
  55. pi.GetValue(propertySet, null))))
  56. {
  57. result = false;
  58. break;
  59. }
  60. }
  61. }
  62. return result;
  63. }
  64. private void TestRouteFail(string url)
  65. {
  66. // Arrange
  67. RouteCollection routes = new RouteCollection();
  68. RouteConfig.RegisterRoutes(routes);
  69. // Act - process the route
  70. RouteData result = routes.GetRouteData(CreateHttpContext(url));
  71. // Assert
  72. Assert.IsTrue(result == null || result.Route == null);
  73. }
  74. [TestMethod]
  75. public void TestIncomingRoutes()
  76. {
  77. // check for the URL that we hope to receive
  78. TestRouteMatch("~/Admin/Index", "Admin", "Index");
  79. // check that the values are being obtained from the segments
  80. TestRouteMatch("~/One/Two", "One", "Two");
  81. // ensure that too many or too few segments fails to match
  82. TestRouteFail("~/Admin/Index/Segment");//失败
  83. TestRouteFail("~/Admin");//失败
  84. TestRouteMatch("~/", "Home", "Index");
  85. TestRouteMatch("~/Customer", "Customer", "Index");
  86. TestRouteMatch("~/Customer/List", "Customer", "List");
  87. TestRouteFail("~/Customer/List/All");//失败
  88. TestRouteMatch("~/Customer/List/All", "Customer", "List", new { id = "All" });
  89. TestRouteMatch("~/Customer/List/All/Delete", "Customer", "List", new { id = "All", catchall = "Delete" });
  90. TestRouteMatch("~/Customer/List/All/Delete/Perm", "Customer", "List", new { id = "All", catchall = "Delete/Perm" });
  91. }
  92. }

最后还是再推荐一下Adam Freeman写的apress.pro.asp.net.mvc.4这本书。稍微熟悉MVC的从第二部分开始读好了。

【编辑推荐】

【责任编辑:林琳 TEL:(010)68476606】