zoukankan      html  css  js  c++  java
  • 如何在多个项目中分离Asp.Net Core Mvc的Controller和Areas

    前言

    软件系统中总是希望做到松耦合,项目的组织形式也是一样,本篇文章将介绍在ASP.NET CORE MVC中怎么样将Controller与主网站项目进行分离,并且对Areas进行支持。

    实践

    1.新建项目

    新建两个ASP.NET Core Web应用程序,一个命名为:WebHostDemo 另一个名为: Web.Controllers ,看名字可以知道第一个项目是主程序项目,第二个是存放Controller类和Areas的项目。

    2.修改Mvc配置

    在WebHostDemo项目中修改ConfigureServices函数:

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
    
        var manager = new ApplicationPartManager();
    
        var homeType = typeof(Web.Controllers.Areas.HomeController);
        var controllerAssembly = homeType.GetTypeInfo().Assembly;
    
        manager.ApplicationParts.Add(new AssemblyPart(controllerAssembly));
        manager.FeatureProviders.Add(new ControllerFeatureProvider());
    
        var feature = new ControllerFeature();
    
        manager.PopulateFeature(feature);
    
        services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
    }
    

    这样就将另一个项目中的Controller程序集注入到主程序中了。当然还可以通过另一种方式:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().ConfigureApplicationPartManager( m => {
             var feature = new ControllerFeature();
              m.ApplicationParts.Add(new AssemblyPart(controllerAssembly));
             m.PopulateFeature(feature);
             services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
        });
    }
    

    这两种方式都可以注入Controller。

    接下来修改Configure函数以,通过修改路由让Mvc支持Areas:

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "areaRoute",
            template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
    
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
    

    3.添加Areas

    在Web.Controllers项目中建立如下目录结构:
    Areas

            MyArea1
                -Controllers
                    -Home.cs
                -Views
                    -Home
                        Index.cshtml
    

    4.为Controller添加Area

     [Area("MyArea1")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
    

    最后

    还有一件事很重要,当我们这么将项目进行分离后,DEBUG主程序将没办法找到Areas和Views目录,所以DEBUG时,要将这些目录Copy到主程序代码根目录,当然如果是发布程序的话就没有这个问题。

    GitHub:https://github.com/maxzhang1985/YOYOFx 如果觉还可以请Star下, 欢迎一起交流。

    .NET Core 开源学习群:214741894

    Demo已经上传到群文件中,仅供参考。

  • 相关阅读:
    oracle 时间加减法 与C#
    BCB编写DLL
    面试题:产生一个长度为100的数组,为数组中的每一项随机填充1100之间的数并且保证不重复 (C#实现)
    公司内部员工运算测试题
    MVP 模式是否应该这样修改?
    MVP 模式是否应该这样修改2?
    面试题:一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算法实现(C#)
    使用游标进行跨数据库循环更新
    Hive 安装配置流程
    Scala的基本语法:集合应用
  • 原文地址:https://www.cnblogs.com/maxzhang1985/p/6683263.html
Copyright © 2011-2022 走看看