10

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??

1
  • In another test, I even kept the server startup code in the class library, but just move the controller class to the host application and it works. But any controller in the class library is still ignored. Commented Sep 19, 2022 at 17:35

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

You just saved my sanity since the WebApplicationFactory<Program> tests will not work without this. They just randomly 404 (NotFound) or 405 (MethodNotAllowed). Also writing these here so others searching can find this Answer.
Yup. I often find that marking up interfaces with attributes doesn’t always work and I get 404s. So now I just always add the assemblies in explicitly and it works.
Thanks, another one sanity is saved by your post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.