I have an ASP.Net
WebApi2
project hosting odata both ApiController
and ODataController
.
And I want to add a custom action in an ODataController
.
I saw this seems to be achievable by either adding [HttpPost]
attribute on the desired action, or by configuring the ODataConventionModelBuilder with a specific FunctionConfiguration when using the MapODataServiceRoute.
To distinguish between odata routes and webapi routes we use the following scheme :
- odata : http://localhost:9292/myProject/odata
- webapi : http://localhost:9292/myProject/api
I tried both these solution without success which all led to get an HTTP 404 result.
My custom action is defined as following:
public class SomeModelsController : ODataController
{
//...
[EnableQuery]
public IHttpActionResult Get()
{
//...
return Ok(data);
}
public IHttpActionResult MyCustomAction(int parameterA, int parameterB)
{
//...
return Json(data);
}
//...
}
So as you guessed it, the Get call on the controller perfectly work with odata. However the MyCustomAction is a bit more difficult to setup properly.
Here is what I have tried :
Setting an [HttpPost] attribute on MyCustomAction
[HttpPost] public IHttpActionResult MyCustomAction(int parameterA, int parameterB) { //... return Json(data); }
I also tried decorating MyCustomAction with the
[EnableQuery]
attribute.
Also, I tried adding the[AcceptVerbs("GET", "POST")]
attribute on the method without changes.Configuring the ODataConventionModelBuilder
private static IEdmModel GetEdmModel() { var builder = new ODataConventionModelBuilder { Namespace = "MyApp", ContainerName = "DefaultContainer" }; // List of entities exposed and their controller name // ... FunctionConfiguration function = builder.Function("MyCustomAction ").ReturnsFromEntitySet<MyModel>("SomeModels"); function.Parameter<int>("parameterA"); function.Parameter<int>("parameterB"); function.Returns<MyModel>(); return builder.GetEdmModel(); }
Also tried decoration of MyCustomAction with
[EnableQuery]
,HttpPost
and[AcceptVerbs("GET", "POST")]
attributes.
I still get HTTP 404 result.
My query url is as follow:
http://localhost:9292/myProject/odata/SomeModels/MyCustomAction?parameterA=123¶meterB=123
I also tried to POST parameters on
http://localhost:9292/myProject/odata/SomeModels/MyCustomAction
with the same result. Actually with or without parameters I get HTTP 404 status.