OData routing in Web Api

烈酒焚心 提交于 2019-12-24 04:37:13

问题


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.


回答1:


  1. You should rename your id to key, then http://localhost:52074/api/Ticket(1) will route to Get(1).

  2. If you want to use ODataRoute, the attribute should be like: [ODataRoute("Customers({id})")].

  3. FYI

    OData website

    OData Documentation



来源:https://stackoverflow.com/questions/31985730/odata-routing-in-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!