我有一个带有多个响应模型的 ASP.NET Web Api 2 项目。为了创建更小的有效负载,我为用户提供了将实体折叠为一个 id 和一个 href 链接的选项,我想自动生成这些链接。我希望我所有的主要资源响应模型都继承自只有 href
和 id
的基本响应模型。如果我有一个资源 Foo
,它看起来像这样:
public class ResourceResponseModel
{
public string Href { get; private set; }
public string Id { get; private set; }
protected ResourceResponseModel(string id)
{
Id = id;
}
}
public class FooModel : ResourceResponseModel
{
public string Name { get; private set; }
private ExampleModel (string id, string name)
: base(id)
{
Name = name;
}
internal static FooModel From(Foo foo)
{
return new FooModel(
foo.Id,
foo.Name
);
}
}
当我的 Controller 被调用时,这个模型被序列化为 Microsoft.AspNet.Mvc.Json(object data)
这似乎工作得很好,除了当我查看我最终得到的响应时,它把基类属性放在最后:
{
"name": "Foo 1",
"href": "api/abcdefg",
"id": "abcdefg"
}
有没有简单的方法让基本属性出现在资源属性之前?
最佳答案
您可以通过在属性上设置 JsonProperty
属性并传入 Order
来解决此问题。
public class ResourceResponseModel
{
[JsonProperty(Order = -2)]
public string Href { get; private set; }
[JsonProperty(Order = -2)]
public string Id { get; private set; }
protected ResourceResponseModel(string id)
{
Id = id;
}
}
Order
似乎默认为零,然后在序列化时从低到高排序。可以找到文档 here .
关于c# - 从基类继承 href 和 id 的 ASP.NET WebApi 响应模型中的排序属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35743248/