【发布时间】:2017-08-21 22:46:34
【问题描述】:
我正在尝试在link 之后的现有 ASP.NET Web API 2 服务中添加 OData 查询选项。我只希望查询选项在 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?$select=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
}
【问题讨论】:
-
尝试将 [HttpGet] 更改为 [EnableQuery]。您也可以尝试自己应用选项 opts.SelectExpand.ApplyTo(order);
标签: asp.net asp.net-web-api2 odata