I'm trying to add OData Query Options in an existing ASP.NET Web API 2 service following this link. I only want the query options to be available in GET methods. I haven't been able to work the $select option when I try to get an item by id. How can I achieve this? This is what I have so far:
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);
}
}
When I test it (http://localhost:10240/api/orders/1?$select=OrderId) I have the following result:
{
"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
}
As @mumfy suggested, I missed to apply the options. The last line in GetOrder method left:
return Ok(opts.ApplyTo(Enumerable.Repeat(order, 1).AsQueryable()));