2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > 如何在多个项目中分离Asp.Net Core Mvc的Controller和Areas

如何在多个项目中分离Asp.Net Core Mvc的Controller和Areas

时间:2020-03-12 20:14:04

相关推荐

如何在多个项目中分离Asp.Net Core Mvc的Controller和Areas

前言

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

实践

1.新建项目

新建两个 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-HomeIndex.cshtml

4.为Controller添加Area

[Area("MyArea1")]

public class HomeController : Controller{

public IActionResult Index() {

return View();}}

最后

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

原文地址:/maxzhang1985/p/6683263.html

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。