MVC-区域(Area)

1.启用路由前的准备工作

1.Global.asax.cs中注册路由

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //===============注册区域===============
            AreaRegistration.RegisterAllAreas();
            //===========注册路由======================还可以注册全局过滤器...
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

2.添加域

项目名右键单击--->添加--->区域
再对应的控制器目录下写一个控制器并添加视图
MVC-区域(Area)_第1张图片3
其中adminAreaRegistration.cs与hvAreaRegistration.cs为子路由,,用默认值即可;
此时,http://localhost:33777/admin/home/index与http://localhost:33777/hv/home/index可分别访问对应的域的控制器。

using System.Web.Mvc;
namespace MyMvcAreasDemo.Areas.admin
{
    public class adminAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "admin";
            }
        }
        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "admin_default",
                "admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
using System.Web.Mvc;
namespace MyMvcAreasDemo.Areas.hv
{
    public class hvAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "hv";
            }
        }
        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "hv_default",
                "hv/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

3.App_Start\RouteConfig.cs配置路由

using System.Web.Mvc;
using System.Web.Routing;
namespace MyMvcAreasDemo
{
    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[] { "MyMvcAreasDemo.Areas.admin.Controllers" }
            ).DataTokens.Add("area", "admin");
        }
    }
}

上文注释:
MVC-区域(Area)_第2张图片

你可能感兴趣的:(MVC-区域(Area))