We have 100+ APIs and have to write ProducesResponseType for all our APIS at the top, 200, 500, etc. Is there a method to make this global parameter for all our get functions, so we don't have to continue repeating code? Trying to make APIs follow Dry principle and be thin controllers.
[HttpGet("[Action]/{id}")]
[ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<GetBookResponse>> GetByBook(int id)
{
var book = await bookservice.GetBookById(id);
return Ok(book);
}
Resources:
Set one ProducesResponseType typeof for several HttpStatusCodes
Net Core API: Purpose of ProducesResponseType
You can create a custom IApplicationModelProvider and add the filters you need in OnProvidersExecuting method.
ProduceResponseTypeModelProvider.cs
public class ProduceResponseTypeModelProvider : IApplicationModelProvider
{
public int Order => 3;
public void OnProvidersExecuted(ApplicationModelProviderContext context)
{
}
public void OnProvidersExecuting(ApplicationModelProviderContext context)
{
foreach (ControllerModel controller in context.Result.Controllers)
{
foreach (ActionModel action in controller.Actions)
{
// I assume that all you actions type are Task<ActionResult<ReturnType>>
Type returnType = action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments()[0];
action.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status510NotExtended));
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status200OK));
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status500InternalServerError));
}
}
}
}
Then you need to register it to IServiceCollection
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, ProduceResponseTypeModelProvider>());
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With