我收到以下错误:
The path template ‘GetClients()’ on the action ‘GetClients’ in controller ‘Clients’ is not a valid OData path template. Resource not found for the segment ‘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)
知道我做错了什么吗?
解决方法
您甚至不需要添加这样的函数来获取实体.
builder.EntitySet<ClientModel>("Clients")
是你所需要的全部.
然后将您的行动写为:
public IHttpActionResult GetClientModel([FromODataUri] int key) { return Ok(_clientsRepository.GetClients(key).Single()); }
要么
这是有效的.以上不起作用:
public IHttpActionResult Get([FromODataUri] int key) { return Ok(_clientsRepository.GetClients(key).Single()); }
然后是Get请求
http://localhost/odata/Clients(Id=5)
要么
http://localhost/odata/Clients(5)
将工作.
更新:使用未绑定的函数返回许多ClientModel.
以下代码适用于v4.对于v3,您可以使用操作.
builder.EntitySet<ClientModel>("Clients"); var function = builder.Function("FunctionName"); function.Parameter<int>("Id"); function.ReturnsCollectionFromEntitySet<ClientModel>("Clients");
[HttpGet] [ODataRoute("FunctionName(Id={id})")] public IHttpActionResult WhateverName(int id) { return Ok(_clientsRepository.GetClients(id)); }
发送请求:
GET ~/FunctionName(Id=5)