在这篇教程中,你会学习到如何为ASP.NET MVC应用程序添加自定义路由。你会学习如何将Global.asax文件中的默认路由表修改为自定义路由。
对于简单的ASP.NET MVC应用程序,默认的路由表已经可以很好的完成工作了。然而,你可能发现会存在特定的路由需求。在这种情况下,你可以创建一个自定义路由。
设想一下,举个例子,你正在创建一个博客应用程序。你可能想要像这样处理即将到来的请求:
/LingLing/10-28-1987
当用户输入这一请求,你想要返回对应于日期10/28/1987的博客条目。为了处理这种类型的请求,你需要创建一个自定义路由。
以下代码中的Global.asax包含了一个新的自定义路由,命名为了Blog,它处理了类似/LingLing/条目日期 这样的请求。
using System.Web.Mvc; using System.Web.Routing; namespace MvcApplication1 { public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Blog", // Route name "LingLing/{entryDate}", // URL with parameters new { controller = "LingLing", action = "Entry" } // Parameter defaults ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } } }
添加到路由表中的路由顺序非常重要。我们的新自定义Blog路由在现有的Default路由前面。如果你将这个顺序颠倒过来,那么Default路由将总是被调用,而不是自定义路由。
自定义Blog路由匹配任何以/Archive/作为开始的请求。因此,它匹配所有下面的URL:
/LingLing/12-25-2009
/LingLing/10-6-2004
/LingLing/apple
自定义路由将即将到来的请求映射到名为Archive的控制器,并且调用了Entry()动作。当调用Entry()方法时,条目日期作为entryDate参数进行了传递。
using System; using System.Web.Mvc; namespace MvcApplication1.Controllers { public class ArchiveController : Controller { public string Entry(DateTime entryDate) { return "You requested the entry from " + entryDate.ToString(); } } }
注意到代码 中的Entry()方法接受一个DateTime类型的参数。MVC框架非常的聪明,足以自动地将URL中的条目日期转换为DateTime值。如果URL中的条目日期参数不能转换为DateTime,将会引发错误