NSwag icon indicating copy to clipboard operation
NSwag copied to clipboard

System.Text.Json serialization settings not picked up if MVC not in use

Open mdsharpe opened this issue 1 year ago • 2 comments

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!

mdsharpe avatar Jan 03 '24 11:01 mdsharpe

Encountered the same issue and can confirm the workaround works.

Thanks @mdsharpe

cliedeman avatar Jan 31 '24 20:01 cliedeman

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

schnerring avatar Feb 14 '24 18:02 schnerring

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;
    }
}

JarFrank avatar Feb 22 '24 13:02 JarFrank

Is this still an issue with v14.0.7? I think this PR might have fixed it: https://github.com/RicoSuter/NSwag/pull/4733

RicoSuter avatar Mar 26 '24 17:03 RicoSuter

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.

egresspav avatar Mar 27 '24 19:03 egresspav