user2987281 user2987281 - 4 months ago 88
reST (reStructuredText) Question

Custom GET action in ASP.NET WebAPI 2 OData Controller

I'm using WebApi2 and OData. I want add custom action, and use it by GET method

GET /odata/Providers(2)/DoSth


but I dont understand how it works exactly. Here is code for one of my controller:

public class ProvidersController : ODataController
{
private Entities db = new Entities();

// GET: odata/Providers
[Queryable]
public IQueryable<PROVIDER> GetProviders()
{
return db.PROVIDER;
}
//... OTHER GENERATED METHODS

//MY TEST METHOD SHOULD BE inoked: GET /odata/Providers(2)/DoSth
public int DoSth()
{
return 22;
}
}


and WebApiConfigFile:

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<PROVIDER>("Providers").EntityType.HasKey(o => o.P_ID);
//others entities ...

//my custom action without any parameters, returns int:
ActionConfiguration getTest = builder.Entity<PROVIDER>().Action("DoSth");
getTest.Returns<int>();


Method existing in /odata/$metadata

but cant run this method from the url (still showing 404: "No HTTP resource was found that matches the request URI").

Any ideas how to improve this issue?

Answer

In OData an action can only be invoked by the POST method. So just change the request from GET to POST.

If it doesn't work, add an attribute to the method in the controller:

[HttpPost]
public int DoSth()
{
    return 22;
}

If you just start to play with OData, I recommend you start from OData V4, which is an OASIS standard. Here is a sample about actions: https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataActionsSample/ .