学习笔记:ASP.NET MVC之路由

说来惭愧,已经做了几个公司的项目,但是还没有系统的学习过ASP.NET MVC。就简单的凭以前的经验,然后遇到问题google一下,竟然也做完了项目。现在有点小空,准备系统的看一下MVC,下面记录一些我的学习笔记,方便以后查阅。
1. 当你运行一个ASP.NET MVC的项目时,一个路由表在程序运行一开始就已经建立了。相关的代码在global.asax里面。程序一开始会与性Application_Start(), 注册你的路由规则到RouteTable.Routes中去。
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;d
using System.Web.Routing;

namespace MVCApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(
"{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

}

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterRoutes(RouteTable.Routes);
}
}
}      
 
当你输入URL:Home/Index/3
这个URL正好匹配到默认的路由,简单的说就是Controller=Home, Action=Index, id=3
程序就会调用HomeController.Index(3)
 
 
如何增加一个自定义的路由
 
比如你需要显示一个归档的blog列表。你希望URL是这样的Archive/04-07-2011,那么你的路由则应该如此定义。
 
routes.MapRoute(
"Blog", // Route name
"Archive/{entryDate}", // URL with parameters
new { controller = "Archive", action = "Entry" } // Parameter defaults
);
 
当你输入Archive/04-07-2011,程序会执行到ArchiveController.Entry(DateTime enteryDate)。 那么这时候如果你输入的Archive/MVC, 你就会得到一个报错,因为"MVC"只是一个string类型,并不是DateTime的。
如何做到避免这种情况的发生呢。就需要给这个路由建立一个约束。
 
如何给路由建立一个约束
 
routes.MapRoute(
"Blog", // Route name
"Archive/{entryDate}", // URL with parameters
new { controller = "Archive", action = "Entry" }, // Parameter defaults
new { entryDate = @"\d{2}-\d{2}-\d{4}" }
);
 
当然了,我这个日期的约束是简单的约束,只是举个例子。
这样,那些不符合我们要求的URL,比如Archive/MVC,就不会匹配到这个路由了,它就会去找其他的路由来匹配,当然如果匹配不到的话,还是会报错的。
好了,今天就记录到这里。后面看到了新的再写了:)
posted @ 2011-04-07 21:28  看花开花落  阅读(2028)  评论(9编辑  收藏  举报