Adding [ApiController] on a controller class has various benefits. Especially the automatic model validation and problem details parts.

The problem with this attribute is that it's easy to forget to add it, so I want to add it globally in one place.

One way to do that is to add this line somewhere in the project.

[assembly: ApiController]

My architecture is a modular monolith, with a single API project that registers controllers from other projects using ConfigureApplicationPartManager . That means that I would need to add [assembly: ApiController] to each project to have it auto applied.

Is there a better way?

3 Replies 3

Another option according to the docs is to create a base class with aforementioned attribute:

[ApiController]
public class MyControllerBase : ControllerBase
{
}

And inherit all controllers in other assemblies from it:

[Produces(MediaTypeNames.Application.Json)]
[Route("[controller]")]
public class SomeController : MyControllerBase

This has a potential benefit of sharing some other stuff too.

Yeah I saw that one, but we're already using ControllerBase in all places and it's easy to forget to use the base class as well, so I want a fully fool-proof solution.

You can write unit tests that will check for the attribute on the controllers. So it won't be possible to forget it.
ArchUnitNET may help with this.

Your Reply

By clicking “Post Your Reply”, 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.