c# - Controller 中操作的路径模板不是有效的 OData 路径模板

标签 c# asp.net-web-api odata asp.net-web-api-routing asp.net-web-api-odata

我收到以下错误:

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'.

我的 Controller 方法是这样的

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")

就是你所需要的。

然后把你的 Action 写成:

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)

会起作用。

更新:使用未绑定(bind)函数返回多个 ClientModel。

以下代码适用于 v4。对于 v3,您可以使用操作。

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

在 Controller 中添加一个方法,如:

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

发送如下请求:

GET ~/FunctionName(Id=5)

关于c# - Controller 中操作的路径模板不是有效的 OData 路径模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24602935/

相关文章:

c# - 如何使用 .net 创建加密文件容器

c# - 通过 Web API 将文件流上传到 StreamReader

treeview - UI5树表为什么重复节点?

c# - 将自定义设计时命令添加到 WinForms 控件

c# - 如何使大型 if 语句更具可读性

c# - ASP.NET Web API 的 CaSTLe Windsor ApiController Factory 实现

entity-framework - 如何在 ASP.NET MVC 5 中为同一个 OData Controller 设置多个实体集

odata - Simple.OData.Client - 无法调用接受实体集合参数的操作

c# - 将鼠标指针移动到选项卡按钮将您带到的位置 C#

asp.net-web-api - 为 ApiController 之外的 asp.net web api 中的资源生成 url