• mvc4 基于Area实现插件模块化开发


      对于一个较大规模的Web应用,可以从功能上通过Area将其划分为为较小的单元。每个Area相当于一个独立的子系统,具有一套包含Model、Views和Controller在内

    的目录结构和配置文件。一般来说,每个Area具有各自的路由规则,而基于Area的路由映射通过System.Web.Mvc.AreaRegistration注册。

      先来看下整体结构:

      

           LoonMvc4是正常的mvc4项目,loon.plugin1和loon.plugin2是普通类库项目,接下来我们来看下怎么使得loog.plugin1成为一个独立的模块。

      

              loon.plugin1是普通的类库项目。我们需要在类库中加入对mvc的支持,诸如引入:system.Web,System.Web.Mvc等使得该类库具有mvc的特质。接下来比较重要的一步,Area隆重登场,这里边需要注意,使用area 路由的话,引用必须包含System.Web.Mvc后方才可以使用。仔细看上边示意图,有一个文件名字较长就是“LoonPlugin1AreaRegistration.cs”。我们来关注一下LoonPlugin1AreaRegistration.cs这个文件。我们来看内部代码:

    namespace loon.plugin1
    {
        public class LoonPlugin1AreaRegistration : AreaRegistration
        {
            public override string AreaName
            {
                get { return "LoonPlugin1"; }
            }
            public override void RegisterArea(AreaRegistrationContext context)
            {
                context.MapRoute(
                "LoonPlugin1",//路由名字,必须唯一
                "LoonPlugin1/{controller}/{action}/{id}",//路由规则
                new { controller = "Test", action = "Index", id = UrlParameter.Optional }//默认值
                );
            }
        }
    }

    注:要使我们的Area发挥作用,必须继承AreaRegistration,而且我们的LoonPlugin1AreaRegistration 类的修饰符必须为 public。

          完成了解完以上的代码之后,我们在loon.plugin1中创建一个controller,作为测试.如我们创建一个CustomerController.代码如下:

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Collections.Generic;
    using loon.plugin1.Domain;
    using loon.plugin1.Repository;
    using Microsoft.Practices.Unity;
    
    namespace loon.plugin1
    {
        public class CustomerController : Controller{
    
            [Dependency]
            public CustomerRepository customerRepository{get;set;}
    
            [HttpGet]
            public ActionResult Index()
            {
                //Dictionary<string, object> dic = new Dictionary<string, object>();
                //dic.Add("id", 100);
                //dic.Add("name", "hello");
    
                
                return Json(new {customer=this.customerRepository.GetAll(),message="loon.plugin1.CustomerController"}, JsonRequestBehavior.AllowGet);  
            }
        }
    }

      我们还有重要的一步需要设置:在loon.plugin1类库中属性,将其生成目录放到LoonMvc4下,这一步超级重要,生成到主项目目录下之后,mvc就会根据路由找到并解析路由地址并完成请求:如图所示

     

     

      loon.plugin2的创建和配置和loon.plugin2一样。

      然后整体运行解决方案,点击F5.

    注:我们可以反回去看一下,LoonPlugin1是我们loon.plugin1中定义路由的名字,customer是Controller的名字。

    你看懂了吗?至于customer中的值是怎么来的,欢迎关注我么下篇博客 mvc4+nhibernate+mysql 插件式编程。

    如果有什么问题,欢迎批评指正。

              

  • 相关阅读:
    Java 编程基础
    LING 实战
    C# 3.0\3.5 新特性
    EF Code First 入门
    C# 4.0 新特性
    JavaScript学习(二)
    JavaScript学习(一)
    csdn的blog后台程序的导航菜单的实现
    HashTable的遍历
    开通啦
  • 原文地址:https://www.cnblogs.com/gaolizhong/p/4387674.html
Copyright © 2020-2023  润新知