Areas是ASP.NET Mvc 2.0版本中引入的眾多新特性之一,它可以幫你把一個較大型的Web項目分成若干組成部分,即Area。實現Area的功能可以有兩個組織形式:
- 在1個ASP.NET Mvc 2.0 Project中建立Areas。
- 建立多個ASP.NET Mvc 2.0 Project,每個Project就是一個Area。
第2種結構比較複雜,但第1種結構同樣可以做到每個Area之間的並行開發,互不影響,所以不推薦第2種方法。
以ASP.NET Mvc 2.0的預設範本為例:
1. 首先要建立一個ASP.NET Mvc 2.0的Project,在Project上點擊滑鼠右鍵選擇Add->Area,在開啟的視窗中輸入Area的名子(例如:Profile),點擊Add按鈕,然後將看到下面的結構。
名子叫做Profile的Area的結構與根目錄下的Controllers,Models和Views的結構是一樣的,唯一區別是Profile下面多了一個ProfileAreaRegistration.cs檔案。它繼承自AreaRegistration類,ProfileAreaRegistration 必須實現AreaRegistration類中的AreaName屬性和RegisterArea(AreaRegistrationContext context)方法
using System.Web.Mvc;namespace ASP.NET_Mvc_2_Test.Areas.Profile{ public class ProfileAreaRegistration : AreaRegistration { public override string AreaName { get { return "Profile"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Profile_default", "Profile/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } }}
AreaName屬性用來定義Area的名子, RegisterArea(AreaRegistrationContext context) 方法中可以看出在瀏覽器的地址欄中URL的樣式為Profile/{controller}/{action}/{id},是4級構結,只要將context.MapRoute(…)改為
public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Profile_default", "Profile/{action}/{id}", new { controller = "要訪問的controller名子", action = "Index", id = UrlParameter.Optional } ); }
URL的樣式會再變為三級結構 Profile/{action}/{id}。
2. 修改根目錄下Views/shared/Site.Master檔案,並添加一個名為o”Your Profile”的功能表項目並指定area的名子, 樣本中Area的名子為Profile。
<ul id="menu"> <li><%= Html.ActionLink("Home", "Index", "Home", new { area = ""}, null)%></li> <li><%= Html.ActionLink("Your Profile", "ViewProfile", "Profile", new { area = "Profile" }, null)%></li> <li><%= Html.ActionLink("About", "About", "Home", new { area = ""}, null)%></li></ul>
注意:Home和About不屬於任何Area,但是也要通過匿名對象的方式聲明area,如果沒有聲明Area,當進入到Profile的某個view時, Home和About的會的URL會變為Profile/Home, Profile/About,點擊Home或About時會有異常拋出,所以當頁面上的某個連結不屬於任何一個Area並且有可能被多個Area可享的話,一定要加上new { area = ""}
3. 只有匹配正確的Route才能顯示Area中的View,Area中的Route已經配置好,但它是如何被加入到RouteTable中的?
3.1 首先在Global.asax.cs的Application_Start()方法中調用了AreaRegistration.RegisterAllAreas()方法,這個方法的目地主是找出所有繼承了AreaRegistration的類,並執行RegisterArea(…)方法來完成註冊
public static void RegisterAllAreas() { RegisterAllAreas(null); } public static void RegisterAllAreas(object state) { RegisterAllAreas(RouteTable.Routes, new BuildManagerWrapper(), state); } internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state) { List<Type> areaRegistrationTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(_typeCacheName, IsAreaRegistrationType, buildManager); foreach (Type areaRegistrationType in areaRegistrationTypes) { AreaRegistration registration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType); registration.CreateContextAndRegister(routes, state); } }
3.1.1 TypeCacheUtil.GetFilteredTypesFromAssemblies(…)方法用來找出所有繼承了AreaRegistration類的Type對象:
public static List<Type> GetFilteredTypesFromAssemblies(string cacheName, Predicate<Type> predicate, IBuildManager buildManager) { TypeCacheSerializer serializer = new TypeCacheSerializer(); // first, try reading from the cache on disk List<Type> matchingTypes = ReadTypesFromCache(cacheName, predicate, buildManager, serializer); if (matchingTypes != null) { return matchingTypes; } // if reading from the cache failed, enumerate over every assembly looking for a matching type matchingTypes = FilterTypesInAssemblies(buildManager, predicate).ToList(); // finally, save the cache back to disk SaveTypesToCache(cacheName, matchingTypes, buildManager, serializer); return matchingTypes; }
在GetFilteredTypesFromAssemblies(…)方法中,先從緩衝中讀取匹配的類型(緩衝用於.Net Framework 4.0中,樣本程式用VS2008在.NET 3.5環境下,暫不討論緩衝的應用)。緩衝沒有資料返回,調用FilterTypesInAssemblies(…)方法返回List<Type>對象, 這時返回的List<Type>才是繼承了AreaRegistration類的Type對象, 下面的代碼是FilterTypesInAssemblies方法的源碼:
private static IEnumerable<Type> FilterTypesInAssemblies(IBuildManager buildManager, Predicate<Type> predicate) { // Go through all assemblies referenced by the application and search for types matching a predicate IEnumerable<Type> typesSoFar = Type.EmptyTypes; ICollection assemblies = buildManager.GetReferencedAssemblies(); foreach (Assembly assembly in assemblies) { Type[] typesInAsm; try { typesInAsm = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { typesInAsm = ex.Types; } typesSoFar = typesSoFar.Concat(typesInAsm); } return typesSoFar.Where(type => TypeIsPublicClass(type) && predicate(type)); }
與尋找controll的方法相似,找出所有assembly中的所有Type並通過TypeIsPublicClass和predicate的過濾出繼承了AreaRegistration類的Type對象
3.1.2 在GetFilteredTypesFromAssemblies(…)方法中如果.Net Framework的版本不是4.0, 最後的SaveTypesToCache(…)方法也不會執行
以後會對.Net Framework 4.0下的ReadTypesFromCache(…)和SaveTypesToCache(…)進行補充
3.2 遍曆返回的List<Type>對象,反射出AreaRegistration 對象並調用它的CreateContextAndRegister(…)方法
internal void CreateContextAndRegister(RouteCollection routes, object state) { AreaRegistrationContext context = new AreaRegistrationContext(AreaName, routes, state); string thisNamespace = GetType().Namespace; if (thisNamespace != null) { context.Namespaces.Add(thisNamespace + ".*"); } RegisterArea(context); }
在CreateContextAndRegister(…)方法中建立一個AreaRegistrationContext 對象並做為RegisterArea(…)方法的參數,RegisterArea剛好是AreaRegistration 的繼承類中重寫方法,在RegisterArea方法只要調用AreaRegistrationContext 類的MapRoute(…)方法就可能完成一個新的Route的註冊。
【範例程式碼 下載】