13

我收到以下错误:

控制器“客户端”中操作“GetClients”的路径模板“GetClients()”不是有效的 OData 路径模板。未找到段“GetClients”的资源。

我的控制器方法看起来像这样

public class ClientsController : ODataController
{
    [HttpGet]
    [ODataRoute("GetClients(Id={Id})")]
    public IHttpActionResult GetClients([FromODataUri] int Id)
    {
        return Ok(_clientsRepository.GetClients(Id));
    }
}

我的WebAPIConfig文件有

builder.EntityType<ClientModel>().Collection
       .Function("GetClients")
       .Returns<IQueryable<ClientModel>>()
       .Parameter<int>("Id");

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: "odata",
    model: builder.GetEdmModel());

我希望能够像这样调用odata rest api:

http://localhost/odata/GetClients(Id=5)

知道我做错了什么吗?

4

2 回答 2

12

You don't even need to add such a function to get an entity.

builder.EntitySet<ClientModel>("Clients")

is all you need.

And then write your action as:

public IHttpActionResult GetClientModel([FromODataUri] int key)
{    
      return Ok(_clientsRepository.GetClients(key).Single());
}

Or

This is what worked. The above did not work:

public IHttpActionResult Get([FromODataUri] int key)
{    
    return Ok(_clientsRepository.GetClients(key).Single());
}

Then the Get request

http://localhost/odata/Clients(Id=5)

or

http://localhost/odata/Clients(5)

will work.

Update: Use unbound function to return many ClientModels.

The follow code is for v4. For v3, you can use action.

builder.EntitySet<ClientModel>("Clients");
var function = builder.Function("FunctionName");
function.Parameter<int>("Id");
function.ReturnsCollectionFromEntitySet<ClientModel>("Clients");

Add a method in the controller like:

[HttpGet]
[ODataRoute("FunctionName(Id={id})")]
public IHttpActionResult WhateverName(int id)
{
    return Ok(_clientsRepository.GetClients(id));
}

Send a request like:

GET ~/FunctionName(Id=5)
于 2014-07-09T08:23:11.463 回答
-1

这条路线不正确:[ODataRoute("GetClients(Id={Id})")]

它应该是:[ODataRoute("Clients({Id})")]

网址应为:http://localhost/odata/Clients(Id=5)

于 2014-07-07T16:51:24.163 回答