4

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?

2
  • 4
    Please could you elaborate This does not seem to be working.? Provide your tried code would be great also Commented Feb 21, 2013 at 6:19
  • Remember that attribute inheritance is a two-way thing - an attribute must be marked as inheritable; as well as code looking for an attribute must specify that it wants to see inherited ones. Are you controlling both of those aspects? Commented Feb 21, 2013 at 7:10

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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);
    }
}

Comments

0

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";
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.