6

I have created an out of the box ASP.NET Core 6 Web API project.

When I launch the project I can see Swagger loaded, displaying a single WeatherForecast endpoint which works when tested.

enter image description here

However, when I launch the Web API project from another .NET Core app, the controllers are not discovered. Swagger returns the following message for reference. Also manually calling the endpoint Url fails.

enter image description here

After some investigation into this issue, I found that if I register the WeatherForecast controller manually it will become visible in Swagger and accessible when requested.

enter image description here

Why is the WeatherForecast controller not being discovered when running the ASP.NET app from another .NET Core App ?

Source Code: GitHub

TheLegendaryCopyCoder
  • 1,658
  • 3
  • 25
  • 46
  • Looks like it scans only executing assembly and skip others until you specify one – Serhii Feb 10 '22 at 14:27
  • 3
    [This answer](https://stackoverflow.com/a/59121354/124386) covers .NET Core 3; maybe it still applies to .NET 6? – Richard Deeming Feb 10 '22 at 14:47
  • @RichardDeeming thanks, yes, its similar to the AddApplicationPart code I used to work around the problem. It is concerning that this issue was raised in .NET Core 3 and still has not been properly addressed in .NET Core 6. I wonder now if its an intentional design characteristic or a bug in the .NET Core code. – TheLegendaryCopyCoder Feb 11 '22 at 10:08

2 Answers2

6

Using the answer linked to by @RichardDeeming I was able to get it to work in .Net 6. Find AddControllers in Program.cs and adapt it to look like this (substitute TestServiceController for one of your controllers that is in the target assembly):

var assembly = typeof(TestServiceController).Assembly;

builder.Services.AddControllers()
                .PartManager.ApplicationParts.Add(new AssemblyPart(assembly) );
Vaccano
  • 78,325
  • 149
  • 468
  • 850
2

Have you tried this:

builder.Services.AddMvc()
                .AddApplicationPart(typeof(WeatherForecastController).Assembly)
                .AddControllersAsServices();
DHasuda
  • 66
  • 6