c# – 控制器中操作的路径模板不是有效的OData路径模板

前端之家收集整理的这篇文章主要介绍了c# – 控制器中操作的路径模板不是有效的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’.

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

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)
原文链接:https://www.f2er.com/csharp/91852.html

猜你在找的C#相关文章