8

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?

2 Answers 2

1

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.

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

1 Comment

Hi Aliostad, I updated my question to reflect your changes. I'm still getting some problems here, but your suggestions were helpful to me. Thanks.
0

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.

1 Comment

Right now, I just have the default route routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); In my actual code, I do have (RectangleController) and (SquareController)... but it is still not routing correctly, giving me the same error message.

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.