Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API - using a base class

In ASP.NET MVC it is possible to create a ControllerBase class that inherits from Controller. Then you can have all of your Controllers inherit from ControllerBase and if you want to have all of your controllers receive a certain attribute, all you have to do is add it to ControllerBase and you're set.

I'm trying to do the same thing with Web API and the ApiController. I've created a base ApiControllerBase class which is decorated with an attribute and then I inherit from ApiControllerBase on all of my ApiControllers. This does not seem to be working.

I do have standard MVC Controllers exhibiting the behavior from attribute they are receiving from my BaseController. And I am able to decorate an ApiController class specifically with my attributes and it works, but I'm not able to get it to work when I'm trying to use the ApiControllerBase class.

Any ideas what I may be doing wronge?

like image 505
jdavis Avatar asked Oct 21 '25 06:10

jdavis


2 Answers

Do note that MVC attributes can not be used by Api controllers and vice versa.

You have to use attributes from the System.Web.Http namespace for Api controllers and attributes from the System.Web.Mvc namespace for regular controllers. If you create your own attributes make sure that they inherit an attribute from the correct namespace.

like image 164
jgauffin Avatar answered Oct 23 '25 20:10

jgauffin


I can confirm the below works. I am not sure exactly what your problem may be without some posted code.

public class BaseApiController : ApiController
{
    public readonly KiaEntities Db = KiaEntities.Get();
}

public class ColorsController : BaseApiController
{
    // GET api/colors
    [Queryable]
    public IEnumerable<ColorViewModel> Get()
    {
        var colors = Db.Colors;
        return Mapper.Map<IEnumerable<ColorViewModel>>(colors);
    }
}
like image 3
TYRONEMICHAEL Avatar answered Oct 23 '25 20:10

TYRONEMICHAEL



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!