I'm developing a REST Api using ASP.NET Core. I want to force the application to produce JSON responses which I can achive decorating my controllers with the "Produces" attribute. Example:
[Produces("application/json")]
public class ProductsController : ControllerBase
{
...
}
But according to this article: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting the filter can be applied globally, but I can't really figure out how.
Is there anyone out there that could provide a simple example of how to apply the "Produces" filter globally?
Filters cannot be applied to Razor Page handler methods. They can be applied either to the Razor Page model or globally.
To apply the filter to all Web API controllers, add it to GlobalConfiguration. Filters. public static class WebApiConfig { public static void Register(HttpConfiguration config) { config. Filters.
Adding Filter scope and Order of execution A filter can be added to the pipeline at one of three scopes: by action method, by controller class or globally (which be applied to all the controller and actions). We need to register filters in to the MvcOption. Filters collection within ConfigureServices method.
The linked documentation tells it already, you just have to read carefully and follow the link ;)
See Filters to learn more, including how to apply filters globally.
and when you follow the link you find an sample:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(typeof(SampleActionFilter)); // by type
options.Filters.Add(new SampleGlobalActionFilter()); // an instance
});
services.AddScoped<AddHeaderFilterWithDi>();
}
In your case:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.Filters.Add(new ProducesAttribute("application/json"));
});
}
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