2017-08-21 86 views
0

我想补充的OData查询选项在现有的ASP.NET Web API服务2跟随此link。我只希望查询选项在GET方法中可用。当我试图通过ID获取项目时,我无法使用$ select选项。我怎样才能做到这一点?这是我到目前为止有:

public class OrdersController : ApiController 
{ 
    private readonly IOrderService orderService; 

    public OrdersController(IOrderService orderService) 
    { 
     this.orderService = orderService; 
    } 

    [HttpGet] 
    [Route("api/orders/{id}", Name = "GetOrderById")] 
    [ResponseType(typeof(Order))] 
    public IHttpActionResult GetOrder(ODataQueryOptions<Order> opts, [FromUri] int id) 
    { 
      Order order = orderService.GetOrderById(id); 
      if (order == null) 
      { 
       return NotFound(); 
      } 

      if (opts.SelectExpand != null) 
       Request.ODataProperties().SelectExpandClause = opts.SelectExpand.SelectExpandClause; 

      return Ok(order); 
    } 
} 

当我测试它(?http://localhost:10240/api/orders/1 $选择=的OrderId)我有以下结果:

{ 
    "OrderId": 1, 
    "ExternalId": "S001", 
    "TransactionType": "I", 
    "BusinessAssociateId": 1, 
    "DeliveryDate": "2017-06-30T21:08:50.427", 
    "Priority": 5, 
    "OrderType": "A", 
    "Status": "F", 
    "Information": "Incoming Material", 
    "Device": "1", 
    "BusinessAssociateName": null, 
    "BusinessAssociateStreet": null, 
    "BusinessAssociateCity": null, 
    "OrderDetails": null 
} 
+0

尝试改变[HTTPGET]至[EnableQuery]。您也可以尝试自己应用这些选项,opts.SelectExpand.ApplyTo(order); – mumfy

回答

0

由于@mumfy建议,我错过了应用选项。在GetOrder方法的最后一行留下:

返回OK(opts.ApplyTo(Enumerable.Repeat(顺序1).AsQueryable()));

相关问题