gpt4 book ai didi

c# - OData v4 自定义函数

转载 作者:太空狗 更新时间:2023-10-29 21:39:12 25 4
gpt4 key购买 nike

我正在尝试在 OData v4 Web API 解决方案中创建自定义函数。我需要根据 OData 无法本地处理的独特逻辑返回“订单”集合。我似乎无法弄清楚如何在不破坏整个 OData 服务层的情况下创建此自定义函数。当我用 ODataRoute 属性装饰 Controller 方法时,一切都会变得糟糕。任何基本请求都会产生相同的错误。有人可以看看下面的代码,看看您是否注意到我一定遗漏了什么?

WebApiConfig.cs

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

config.MapODataServiceRoute("odata", "odata", model: GetModel());
}

public static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Account>("Accounts");
builder.EntitySet<Email>("Emails");
builder.EntitySet<PhoneNumber>("PhoneNumbers");
builder.EntitySet<Account>("Accounts");
builder.EntitySet<Address>("Addresses");
builder.EntitySet<Order>("Orders");
builder.EntitySet<OrderDetail>("OrderDetails");

var orders = builder.EntityType<Order>();
var function = orders.Function("GetByExternalKey");
function.Parameter<long>("key");
function.ReturnsCollectionFromEntitySet<Order>("Orders");

return builder.GetEdmModel();
}
}

OrdersController.cs

public class OrdersController : ODataController
{
private SomeContext db = new SomeContext();

...Other Stuff...

[HttpGet]
[ODataRoute("GetByExternalKey(key={key})")]
public IHttpActionResult GetByExternalKey(long key)
{
return Ok(from o in db.Orders
where //SpecialCrazyStuff is done
select o);
}
}
}

当针对 OData 层发出任何请求时,我收到以下错误响应。

The path template 'GetByExternalKey(key={key})' on the action 'GetByExternalKey' in controller 'Orders' is not a valid OData path template. Resource not found for the segment 'GetByExternalKey'.

最佳答案

根据模型构建器,函数 GetByExternalKey 是一个绑定(bind)函数。根据OData Protocol v4,通过命名空间或别名限定named来调用绑定(bind)函数,所以需要在route属性中增加:

[HttpGet]
[ODataRoute("Orders({id})/Your.Namespace.GetByExternalKey(key={key})")]
public IHttpActionResult GetByExternalKey(long key)
{
return Ok(from o in db.Orders
where//SpecialCrazyStuff is done
select o);
}

如果您不知道命名空间,只需在方法 GetModel() 中添加以下内容:

builder.Namespace = typeof(Order).Namespace;

并将“Your.Namespace”替换为 Order 类型的命名空间。

这里有2个与你的问题相关的例子,仅供引用: https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataFunctionSample/

https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataAttributeRoutingSample/

关于c# - OData v4 自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25268224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com