【问题标题】:Use $select OData Query Option in ASP.NET Web API 2 service在 ASP.NET Web API 2 服务中使用 $select OData 查询选项
【发布时间】: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


【解决方案1】:

正如@mumfy 建议的那样,我错过了应用这些选项。 GetOrder 方法的最后一行:

返回 Ok(opts.ApplyTo(Enumerable.Repeat(order, 1).AsQueryable()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多