Reputation: 21
It needs to in ascending order in swagger sample request body type for the data contract deserialiser to deserialise it?
What do I do to get that working?For example this is the sample XML schema generated by swagger.
<SaveJourney>
<ShipmentTag>test123</ShipmentTag>
<SavedByUserId>test123</SavedByUserId>
<ShipmentId>bf8195f9-caf5-460d-b7a6-d23d6c9e1904</ShipmentId>
<JourneyId>7</JourneyId>
</SaveJourney>
I need this to be sorted in alphabetical order so that the data contract deserialser to deserialise it.
Upvotes: 1
Views: 1520
Reputation: 1176
using swagger 3, dotnet core 3.1 place in Startup.cs
public class SortModelDocumentFilter : Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var schemas = swaggerDoc.Components.Schemas.OrderBy(x=>x.Key).ToDictionary(x=>x.Key,y=>y.Value);
swaggerDoc.Components.Schemas.Clear();
Console.WriteLine($"{schemas?.Count}");
foreach (var prop in schemas)
{
swaggerDoc.Components.Schemas.Add(prop.Key, prop.Value);
}
int k = 0;
foreach (var schema in schemas) Console.WriteLine($"{k++}. {schema.Key}");
}
}
and in ConfigureServices(IServiceCollection services) add
services.AddSwaggerGen(x => {
...
x.DocumentFilter<SortModelDocumentFilter>();
});
Upvotes: 1
Reputation: 17614
The order you see in the sample is exactly what you have in your model.
If you want to change the order just change your model.
Here is an example:
http://swashbuckletest.azurewebsites.net/swagger/ui/index?filter=Dict#/Dictionary/Dictionary_PostEcho
Here is the code behind that controller:
https://github.com/heldersepu/SwashbuckleTest/blob/master/Swagger_Test/Controllers/DictionaryController.cs#L25
If changing the model is not an option, you could create an IDocumentFilter to transform the final SwaggerDocument to suit your needs, here i have some samples:
https://github.com/heldersepu/SwashbuckleTest/blob/master/Swagger_Test/App_Start/SwaggerConfig.cs#L301
Upvotes: 0