如何在多个项目中分离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到主程序代码根目录,当然如果是发布程序的话就没有这个问题。

原文地址:http://www.cnblogs.com/maxzhang1985/p/6683263.html


.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值