asp.net-mvc - 如何在 ASP.NET Core 3.0 的另一个程序集中使用控制器?
问题描述
默认的 dotnet core 3 web api 模板假定控制器与Startup.cs
如何让它知道不同程序集中的控制器?
我个人喜欢让我的解决方案更加分层,并且只取决于它需要依赖的内容
MyApp.Host --> MyApp.WebApi --> MyApp.Application --> MyApp.Domain
所以在MyApp.Host
我不希望对 MVC 框架有任何直接依赖(尽管我知道在 Dotnet Core 3 中这已经是隐含的)。控制器在MyApp.WebApi
解决方案
解决方案是.AddApplicationPart(assembly)
在Startup.cs
.
因此,如果我有
MyApp.WebApi
一个依赖于 nuGet 包的项目:(Microsoft.AspNetCore.Mvc.Core
当前版本为 2.2.5),使用以下控制器:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace MyApp.WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class SamplesController
: ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
var samples =
new List<string>
{
"sample1", "sample2", "sample3"
};
return samples;
}
}
}
我有我Startup.cs
的MyApp.Host
:
using MyApp.WebApi.Controllers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Reflection;
namespace MyApp.Cmd.Host
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var sampleAssembly = Assembly.GetAssembly(typeof(SamplesController));
services
.AddControllers()
.AddApplicationPart(sampleAssembly)
.AddControllersAsServices();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
然后应用程序将检测不同程序集中的控制器,我将能够访问:https://localhost:5001/samples
推荐阅读
- amazon-web-services - AWS 配置历史
- html - 使用 flex 属性时,图像不随其父 div 缩放
- python - 如何在具有 Redis 排队作业的 Flask 应用程序中使用 PostgreSQL 和 SQLAlchemy
- javascript - 阻止所有 cookie 时网站崩溃
- c# - 如何将 DataReceivedHandler 从 Arduino 延迟到 WPF
- azure - 为什么在我的 Azure 应用服务中安装了 python 3.6 版后,python 仍然是 2.7 版?
- javascript - 在其他文件中使用其他文件中的导入模块
- opengl - 如何在不需要任何窗口系统库的情况下使用 OpenGL 渲染到内存?
- sybase - sybase插入数据时出现invalid column name error是什么意思?
- python - 如何对依赖下拉列表进行ajax请求