Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding the "Produces" filter globally in ASP.NET Core

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?

like image 653
Janni Kajbrink Avatar asked Jan 04 '17 11:01

Janni Kajbrink


People also ask

Can filters be applied globally?

Filters cannot be applied to Razor Page handler methods. They can be applied either to the Razor Page model or globally.

How do I register a global filter in Web API?

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.

How do I register a filter in NET Core?

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.


1 Answers

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"));
    });
}
like image 110
Tseng Avatar answered Sep 27 '22 20:09

Tseng