[英]Why is TestServer not able to find controllers when controller is in separate assembly for asp.net core app?
[英]Why is ASP.NET Core 6 not discovering controllers when run from another .NET Core app
我创建了一个开箱即用的 ASP.NET Core 6 Web API 项目。
当我启动项目时,我可以看到 Swagger 已加载,显示一个在测试时有效的 WeatherForecast 端点。
但是,当我从另一个 .NET 核心应用程序启动 Web API 项目时,未发现控制器。 Swagger 返回以下消息以供参考。 手动调用端点 Url 也会失败。
在对此问题进行一些调查后,我发现如果我手动注册 WeatherForecast controller,它将在 Swagger 中可见,并可在请求时访问。
为什么从另一个 .NET 核心应用程序运行 ASP.NET 应用程序时未发现 WeatherForecast controller?
源代码: GitHub
你有没有试过这个:
builder.Services.AddMvc()
.AddApplicationPart(typeof(WeatherForecastController).Assembly)
.AddControllersAsServices();
使用@RichardDeeming链接的答案,我能够让它在.Net 6 中工作。在 Program.cs 中找到AddControllers
并将其调整为如下所示(用TestServiceController
替换目标程序集中的一个控制器):
var assembly = typeof(TestServiceController).Assembly;
builder.Services.AddControllers()
.PartManager.ApplicationParts.Add(new AssemblyPart(assembly) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.