1. Area簡介
ASP.NET MVC Area機制構建專案,可以將相對獨立的功能模組切割劃分,降低專案的耦合度。
2. Area設定Routing
新建Admin Area後,自動建立AdminAreaRegistration.cs,用於設定Area Routing。
using System.Web.Mvc; namespace Libing.Portal.Web.Areas.Admin { public class AdminAreaRegistration : AreaRegistration { public override string AreaName { get { return "Admin"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( name: "Admin_default", url: "Admin/{controller}/{action}/{id}", defaults: new { action = "Index", id = UrlParameter.Optional } ); } } }
在Global.asax.cs的Application_Start(),註冊Area路由。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Libing.Portal.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); // 註冊Area Routing RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
3. 解決預設站點與Area相同Controller名稱的Routing設定
當預設站點與Area中有相同名稱的Controller時,在Routing中新增namespace。
Areas/Admin/AdminAreaRegistration.cs
using System.Web.Mvc; namespace Libing.Portal.Web.Areas.Admin { public class AdminAreaRegistration : AreaRegistration { public override string AreaName { get { return "Admin"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( name: "Admin_default", url: "Admin/{controller}/{action}/{id}", defaults: new { action = "Index", id = UrlParameter.Optional }, namespaces: new string[] { "Libing.Portal.Web.Areas.Admin.Controllers" } ); } } }
App_Start/RouteConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Libing.Portal.Web.Models.Constraints; namespace Libing.Portal.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new string[] { "Libing.Portal.Web.Controllers" } ); } } }
4. 在預設網站與Area網站的連結
@Html.ActionLink("AdminIndex", "Index", new { controller = "Home", area = "Admin" })