数据控制器。更正为什么要实现 get by key

odata controller. Correct why to implement get by key

我从 pluralsight 课程中改编了这个模式。因为能够 return 正确的 http 代码。

public virtual IHttpActionResult Get(int key)
{
    IQueryable<T> result = Repository.AsQueryable().Where(p => p.Id == key);

    if (!result.Any())
        return NotFound();

    return Ok(SingleResult.Create(result));
}

问题出在 return 格式上。

{
   "@odata.context":"https://localhost:44300/odata/$metadata#Reports/$entity","Id":1,"Name":"Test Report#1","Description":"Min f\u00f8rste rapport","CategoryTypeId":1,"OrganizationId":1,"Definition":null,"AccessModifier":"Local","ObjectOwnerId":1,"LastChanged":"2016-08-18T12:57:48.3735722+02:00","LastChangedByUserId":1
}

它在同一个 json 对象中混合了上下文元数据和实体属性。根据 microsoft 的说法,这没有任何问题,只是很难处理。

有没有办法纠正这种行为?

如果您添加带有 application/json; odata.metadata=none 的接受 header,元数据将被删除。