Inherited API API API

I have a couple of classes

Square : Rectangle : Shape (abstract) 

and I have a base controller inheriting from ApiController that I would like to use.

 public abstract class BaseController<T> : ApiController where T : class { public abstract IEnumerable<T> Get() ... } 

and

 public class DerivedController : BaseController<Rectangle> { public override IEnumerable<Rectangle> Get() ... } public class AnotherDerivedController : BaseController<Square> { public new IEnumerable<Square> Get() ... } 

/ api / rectangle will correctly call IEnumerable<Rectangle> Get()

/ api / square will give me an error:

 Multiple actions were found that match the request: System.Linq.IEnumerable`1[Square] Get() on type Web.Api.Controllers.AnotherDerivedController System.Linq.IEnumerable`1[Rectangle] Get() on type Web.Api.Controllers.DerivedController 

If I change public new IEnumerable<Square> Get() to public override IEnumerable<Square> Get() , I get a compile-time error as the reverse signatures differ

How do I get the code to call the appropriate method? Is it necessary to explicitly register each class of methods in RegisterRoutes?

+7
source share
2 answers

You need to override Get, you mainly use it with new . This will not work, as the class will have two Get methods, and the Web API will be confused to choose which one.

You can define BaseController as abstract and Get as virtual or abstract , and then implement it in your DerivedController .

+1
source

You currently have two controllers that can accept your square class. How do you register your routes? If you rename the controllers to rectangleController and SquareController, you'll probably be fine.

0
source