Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapControllers not finding ApiControllers in class library

In .NET 5 this was working, but since moving to .NET 6 and using the more minimal WebApplication to spin up a REST API, I've hit a wall.

To replicate this, I create a simple .NET 6 Console App and in the Main entrypoint, I call:

WebApplicationBuilder builder = WebApplication.CreateBuilder();
builder.Services.AddControllers();
builder.WebHost.ConfigureKestrel(opts => opts.ListenAnyIP(3000));
WebApplication app = builder.Build();
app.UseRouting();
app.MapControllers();
app.Run();

I have a single controller that looks something like this:

[ApiController]
public class SomeController : Controller {
  [HttpGet]
  [Route("/app/{*thing}")]
  public IActionResult DoSomething([FromRoute] String thing) {
    return new ObjectResult("route: " + thing);
  }
}

This all works fine and if I hit localhost:3000/app/foo, the request is routed and I see "route: foo".

But, if I move the Controller and WebApplication startup code into a referenced class library project, (e.g. in a method called Run) the HTTP server spins up and starts listening, but no matter what I do with routing, the controller in the class library is never picked up and every route results in a 404.

Is there a way to still use attribute routing in a class library, or do we now have to use explicit routes??

like image 716
jtalarico Avatar asked Apr 25 '26 03:04

jtalarico


1 Answers

And of course, even though I've been fighting this issue for days, only after I post a StackOverflow question do I stumble upon the answer.

https://github.com/dotnet/aspnetcore/issues/13850

For anyone looking to solve it from here... In the .AddControllers call, you can give the service a hint as to where to find the controllers.

builder.Services.AddControllers().AddApplicationPart(<Assembly Reference>)

Just get a reference to the Reflection.Assembly containing the Controller classes, and they get picked up.

like image 124
jtalarico Avatar answered Apr 28 '26 11:04

jtalarico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!