Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Web API - Add attribute to each controller

I have a project with an ASP.net Web API. Now i have created a custom attribute. I can set that attribute for each controller, but how can i set it on each controller at once? Is there something for in the startup class?

like image 896
Andreas Furster Avatar asked Sep 09 '26 01:09

Andreas Furster


2 Answers

Go to the App_Start > WebApiConfig.cs file.

In the Register method add this line:

config.Filters.Add(new MyCustomAttribute());
like image 171
Andreas Furster Avatar answered Sep 11 '26 19:09

Andreas Furster


1. You can use a base controller and use it as a base class on every of your other controllers.

    [YourCustomAttribute]
    public class BaseController : ApiController 
    {
    }

    public class HomeController : BaseController 
    {
    }

2. Another solution is to use Conditional Filters in ASP.NET MVC 3

Using this solution you can add the attribute without a base class.

like image 36
dknaack Avatar answered Sep 11 '26 18:09

dknaack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!