NunoRibeiro
NunoRibeiro

Reputation: 511

Override a single method from a generic controller

I have an abstract class

public abstract class BaseController<T,K> : ApiController
{
  //several methods

  [Route("{id:int}")]
  public HttpResponseMessage Put(int id, [FromBody]T item)
  {
    //updates the item
  }
}

I have 6 other classes (Controllers) that inherits the BaseController and uses the methods there declared. I need to override the put method on the UserController, and only on the UserController. I´ve tried:

public abstract class BaseController<T,K> : ApiController
{
  //several methods

  [Route("{id:int}")]
  public virtual HttpResponseMessage Put(int id, [FromBody]T item)
  {
    //updates the item
  }
}

public class UserController : BaseController<User, UserDT>
{
  [Route("{id:int}")]
  public override HttpResponseMessage Put(int id, [FromBody]User item)
  {
    //updates the user
  } 
}

but it throws the error: Multiple actions were found that match the request

How can I override the method?

---EDIT---- This is my WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

---EDIT--- added the [Route("{id:int}")]

Upvotes: 0

Views: 409

Answers (1)

Grax32
Grax32

Reputation: 4059

Take the Route attribute off of the override. That is producing 2 identical routes based on the id:int route and the data type of the body. The override will still be executed in place of the base method due to polymorphism.

Upvotes: 1

Related Questions