NSwag
NSwag copied to clipboard
System.Text.Json serialization settings not picked up if MVC not in use
I have a project that is just using Minimal APIs (no MVC). The APIs use camel case serialization but NSwag is outputting pascal case.
I have had to add the following in order for System.Text.Json settings to be used by NSwag:
builder.Services.Configure<Microsoft.AspNetCore.Mvc.MvcOptions>(options =>
{
options.OutputFormatters.Add(
new Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter(
System.Text.Json.JsonSerializerOptions.Default));
});
The relevant area of NSwag code is NSwagServiceCollectionExtensions.AddSwaggerDocument
, where it calls services.GetRequiredService<IOptions<MvcOptions>>()
.
It'd be great if NSwag could use the existing default serializer options, rather than instantiating a new SystemTextJsonSchemaGeneratorSettings
which in turn uses new JsonSerializerOptions()
which doesn't specify camel case.
I appreciate STJ support may be a work-in-progress at the moment!
Encountered the same issue and can confirm the workaround works.
Thanks @mdsharpe
You can also do this:
builder
.Services
.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.PropertyNamingPolicy = null;
});
By default, ASP.NET uses the JsonSerializerDefaults.Web
defaults:
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
NumberHandling = JsonNumberHandling.AllowReadingFromString
You can customize and override the generated client. My client, generated by NSwag, is named 'Client'. To modify its behavior, I simply need to create an additional partial class and define a method within it. This method will then be recognized and utilized during the loading of the JSON settings
public partial class Client
{
static partial void UpdateJsonSerializerSettings(System.Text.Json.JsonSerializerOptions settings)
{
settings.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
}
}
Is this still an issue with v14.0.7? I think this PR might have fixed it: https://github.com/RicoSuter/NSwag/pull/4733
For me v14.0.7 works again as expected . Previous working version was v14.0.3. Thanks @RicoSuter I generate openApi.json from ASP.NET Core project with AddNewtonsoftJson using "$(NSwagExe_Net80) run nswag.json.