苏小弟学习ASP.NET MVC路由扩展
时间:2010-10-16 来源:Steve Ember
http://localhost:2301/hoMe/index
http://localhost:2301/home/index
http://localhost:2301/HOME/INDEX
上面4个地址是否一样?貌似是不一样的,但是有时候客户可能把你的地址写成上面的地址,难道就这样让它报错?或者跳到错误页面?这样是不妥的,我们目前需要做的工作就是不管客户输入的是大写还是小写一概正确,并且调用正确的Action,返回正确的结果,处理方案如下:
1.在visual studio2010里新建一个MVC项目
2.用如下代码替换Global.asax.cs
1 public class MvcApplication : System.Web.HttpApplication
2 {
3 public static void RegisterRoutes(RouteCollection routes)
4 {
5 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
6
7 //routes.MapRoute(
8 // "Default", // Route name
9 // "{controller}/{action}/{id}", // URL with parameters
10 // new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
11 //);
12 //*******************************************************
13
14 routes.Add(new LowercaseRoute("{controller}/{action}/{id}",
15 new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
16 new MvcRouteHandler()));
17
18 }
19
20 protected void Application_Start()
21 {
22 AreaRegistration.RegisterAllAreas();
23
24 RegisterRoutes(RouteTable.Routes);
25 }
26 }
27 public class LowercaseRoute : Route
28 {
29 public LowercaseRoute(string url, IRouteHandler routeHandler)
30 : base(url, routeHandler) { }
31 public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
32 : base(url, defaults, routeHandler) { }
33 public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
34 : base(url, defaults, constraints, routeHandler) { }
35 public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler) { }
36 public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
37 {
38 VirtualPathData path = base.GetVirtualPath(requestContext, values);
39
40 if (path != null)
41 path.VirtualPath = path.VirtualPath.ToLowerInvariant();
42
43 return path;
44 }
45 }
相关阅读 更多 +