Reputation: 8655
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?
Upvotes: 3
Views: 13321
Reputation: 307
I believe the following snippet will help you.
public class HomeController : BaseController
{
public IHttpActionResult Get()
{
base.InitialiseUserState();
var info = Info;
return Ok(info);
}
}
public class BaseController : ApiController
{
public string Info { get; set; }
public void InitialiseUserState()
{
Info = "test";
}
}
Upvotes: 0
Reputation: 101150
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.
Upvotes: 3
Reputation: 4244
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);
}
}
Upvotes: 3