Reputation: 31
I'm trying to enable OData
in Web Api. I created OData
routing, and a controller that inherits from ODataController
, and I want to get some sample data from my application. Here's my code:
public class TicketController : BaseWebApiController //inherits from ODataController
{
[EnableQuery]
public IQueryable<TicketModel> Get()
{
return (_ticketService.GetAll());
}
[EnableQuery]
public SingleResult<TicketModel> Get([FromODataUri] int id)
{
return (_ticketService.Get(id));
}
_ticketService
is a mock service that returns sample data from a static List of TicketModel using AsQueryable()
method. It works fine.
public static class ODataConfig
{
public static void EnableOData(HttpConfiguration config)
{
config.MapODataServiceRoute("odata", "api", GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
config.EnsureInitialized();
}
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<TicketModel>("Ticket");
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
ODataConfig.EnableOData(config)
is then called in App_Start/WebApiConfig.cs
Register method.
The problem is, while url http://localhost:52074/api/Ticket
calls Get()
method properly, a url request of http://localhost:52074/api/Ticket(1)
also calls Get()
instead of Get(1)
. I tried to append ODataRouting("({id})")
attribute but all it does is throw an exception with message
"The path template on the action in controller is not a valid OData path template".
Has anybody had that problem before? Any ideas? Help appreciated.
PS. It's my first question here so if something is missing, let me know.
Upvotes: 2
Views: 11616
Reputation: 2132
You should rename your id
to key
, then http://localhost:52074/api/Ticket(1)
will route to Get(1)
.
If you want to use ODataRoute, the attribute should be like: [ODataRoute("Customers({id})")]
.
FYI
Upvotes: 5