我正在尝试在OData v4 Web API解决方案中创建自定义函数.我需要返回基于OData本身无法处理的独特逻辑的"Orders"集合.我似乎无法弄清楚如何在不破坏整个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("Accounts"); builder.EntitySet ("Emails"); builder.EntitySet ("PhoneNumbers"); builder.EntitySet ("Accounts"); builder.EntitySet("Addresses"); builder.EntitySet ("Orders"); builder.EntitySet ("OrderDetails"); var orders = builder.EntityType (); var function = orders.Function("GetByExternalKey"); function.Parameter ("key"); function.ReturnsCollectionFromEntitySet ("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层发出任何请求时,我收到以下错误响应.
控制器"Orders"中操作"GetByExternalKey"上的路径模板"GetByExternalKey(key = {key})"不是有效的OData路径模板.找不到段'GetByExternalKey'的资源.
Tan Jinfu.. 5
根据模型构建器,函数GetByExternalKey是绑定函数。根据OData协议v4,绑定函数通过命名空间或别名限定的named调用,因此您需要在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/
根据模型构建器,函数GetByExternalKey是绑定函数。根据OData协议v4,绑定函数通过命名空间或别名限定的named调用,因此您需要在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/