ASP.NET WebApi 响应模型中的排序属性从基础 class 继承 href 和 id

Ordering attributes in ASP.NET WebApi response models inheriting href and id from a base class

我有一个 ASP.NET Web Api 2 项目,其中包含多个响应模型。为了创建更小的有效载荷,我为用户提供了将实体折叠为一个 id 和一个 href link 的选项,我想自动生成它们。我希望我所有的主要资源响应模型都继承自只有 hrefid 的基本响应模型。如果我有资源 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
        );
    }
}

当我的控制器被调用时,这个模型被序列化为Microsoft.AspNet.Mvc.Json(object data)

这似乎工作得很好,除了当我查看我最终得到的响应时,它将基本 class 属性放在最后:

{
    "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.