To keep an overview in my Web API, I am using a base controller that contains some basic actions that most of my other controllers use. (E.g. Post([FromBody]JObject newFields)
to add a new item.)
In my project, I have attribute routing enabled. So my base controller looks somewhat like the following:
public class BaseController<T> : ApiController where T : ObjectBase, new()
{
[Route("")]
[ResponseType(typeof(ObjectBase))]
public virtual IHttpActionResult Post([FromBody]JObject newFields)
{
// Post logic
return Ok();
}
}
I am inheriting this base controller in most of the other controllers in my project.
Now for my problem:
In one of my controllers, I want to override this method, because some of the creation logic is different.
This is an example of how I am trying to accomplish that functionality:
[RoutePrefix("api/Users")]
public class UsersController : BaseController<UserObject>
{
[Route("")]
[ResponseType(typeof(ObjectBase))]
public override IHttpActionResult Post([FromBody]JObject newFields)
{
// Overridden post logic
return Ok();
}
}
However, when I now send a POST
request to https://url/api/Users
, I get the following error response:
Message:
An error has occurred.
ExceptionMessage:
Multiple actions were found that match the request:
Post on type WebAPI.Controllers.UsersController
Post on type WebAPI.Controllers.UsersController
ExceptionType:
System.InvalidOperationException
StackTrace:
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()
Anyone who can help me solve this problem?
Thanks in advance!
After trying a lot of things, I finally found a most simple solution. Seems like I just had to remove the attributes in my derived class.
So to follow the example I used in my original post, the UsersController
now looks like this:
[RoutePrefix("api/Users")]
public class UsersController : BaseController<UserObject>
{
public override IHttpActionResult Post([FromBody]JObject newFields)
{
// Overridden post logic
return Ok();
}
}