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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With