Reputation: 235
I have a couple of classes
Square : Rectangle : Shape (abstract)
and I have a Base Controller inheriting from ApiController that I'd 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 properly 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 since the return signatures are different
How do I get my code to call the proper method? Is it necessary to explicitly register each class's methods in RegisterRoutes?
Upvotes: 8
Views: 6968
Reputation: 21231
You currently have two controllers that can take your square class. How are you registering your routes? If you rename the controlers to rectangleController and SquareController you will probably be fine.
Upvotes: 0
Reputation: 81700
You need to override the Get, you are basically using it with new
. This is not gonna work since the class will have two Get methods and Web API will be confused to pick which one.
You may define the BaseController
as abstract
and Get
as virtual
or abstract
and then implement in your DerivedController
.
Upvotes: 1