为什么odata specs为这两个相似的案件返回204和404

时间:2016-04-03 03:00:33

标签: odata

http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part1-protocol.html

11.2.7申请实体参考

如果资源路径终止于单个实体,则响应必须是指向相关单个实体的实体引用的特定于格式的表示。如果资源路径终止于单个实体且不存在此类实体,则服务将返回 404 Not Found

11.2.6申请相关实体

如果关系终止于单个实体,则响应必须是相关单个实体的特定于格式的表示。如果没有相关实体,则服务返回 204无内容

我认为这两种情况类似,它们应该都返回404或204,为什么规范以不同方式定义响应。

1 个答案:

答案 0 :(得分:2)

The spec makes sense. Think of it in terms of an in-memory dictionary of Entity objects indexed by their identity value, and a routing engine that maps URI paths of the form /Entities(x) to the Entity with identity value x.

private static final Map<int, Entity> entities;
static
{
    Entity entity1 = new Entity() {{ id = 1; relatedThing = new Thing() {{ id = 42; }}; }};
    Entity entity2 = new Entity() {{ id = 2; relatedThing = null; }};
    entities = new HashMap<int, Entity>();
    entities.put(entity1.id, entity1);
    entities.put(entity2.id, entity2);
}

Requesting Entity References: If you request /Entities(1)/$ref, dictionary lookup will succeed and you will get a reference to the Entity with id of 1. But if you request /Entities(57)/$ref, the dictionary lookup will fail and you will get an error response (404).

Requesting Related Entities: If you request /Entities(1)/RelatedThing, dictionary lookup will succeed, the OData runtime will dereference the relatedThing property, and you will get a representation of the Thing object associated with the Entity. If you request /Entities(2)/RelatedThing, lookup succeeds, but dereferencing produces null. Note that the navigation property relatedThing exists (because the Entity exists), but there is no associated Thing (i.e., the cardinality of the association is 0..1). Since lookup succeeded, an error response (4xx) is not appropriate. And since dereferencing produced "nothing", the HTTP response code that indicates "no additional content to send in the response payload body" is completely appropriate.