Reputation: 7726
Is it possible to customize the generate Swagger documentation for ASP.NET CORE (C#)? Specifically, it seems to be changing the order properties are displayed in my model (i.e. it puts derived class properties first).
class BaseObj
{
string Username {get;set;}
string Password {get;set;}
}
class Obj2 : BaseObj
{
string SomeotherProp {get;set;}
}
Swagger generates:
SomeotherProp
Username
Password
I want SomeotherProp
to be at the bottom. I've tried using the Display(Order=1) attribute, but Swagger ignores that. I didn't see any hook in the configuration that I can custom sort.
Upvotes: 4
Views: 4866
Reputation: 7726
After a lot of research and trial and error, I stumbled across the answer. Swagger doesn't actually reflect upon your types directly, rather it uses Json.Net to get the type schema. Json.Net respects the JsonProperty attribute. So, on my base type, I can set the JsonProperty=-2 on the properties to get them to show first. Note that you have to use -2 and not -1 since that is reserved. By using -2, you don't have to set JsonProperty on all the derived types.
This will work in my case, but I found another post where the guy defined a custom contract resolver and sorted the properties there... that'll be more generic and cleaner then JsonProperty. Need to figure out how to hook that into Asp.net core though.
But anyways, the point is, the funky ordering is coming from Json.net and not Swagger.
Upvotes: 3