Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to customize the Swagger Schema?

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.

like image 430
SledgeHammer Avatar asked Oct 17 '25 07:10

SledgeHammer


1 Answers

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.

like image 200
SledgeHammer Avatar answered Oct 19 '25 20:10

SledgeHammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!