I have an ASP.NET Web Api 2 project with several response models. In an attempt to create a smaller payload I am offering the user the option to collapse entities to just a id and a href link, which I would like to generate automatically. I would like all my main resource response models to inherit from a base response model that has just the href
and id
. If I have a resource Foo
, this looks something like this:
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
);
}
}
When my controller is called, this model is serialized with Microsoft.AspNet.Mvc.Json(object data)
This seems to work great, except when I look at the response I end up with, it puts the base class attributes at the end:
{
"name": "Foo 1",
"href": "api/abcdefg",
"id": "abcdefg"
}
Is there an easy way to get the base attributes to appear before the resource attributes?
You can solve this by setting the JsonProperty
attribute on you properties and pass in 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
seems to default to zero and then get sorted from low to high when serialized. Documentation can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With