ASP.NET MVC系列:Area
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" })