Swagger UI shows camelCase parameters instead of PascalCase
Asked Answered
G

2

12

I am using NewtonSoft.json in Asp.Net Core 3.1 API with Swashbuckle.AspNetCore version 5.3.3.

By default in Asp.Net Web API, 2 input and output parameter case was PascalCase.

Now I am migrating to .Net Core API in which default case is camelCase.

So I changed it to use PascalCase by adding below code in Startup.cs:

services.AddControllers()
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            })
            .AddNewtonsoftJson(options =>
            {
                // Use the default property (Pascal) casing
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });//Configure Newtonsoft as JSON serializer.

But in the Swagger UI, it is showing input and output parameters in camelCase while the API's response contains values in PascalCase.

I Googled but found a method in AddSwaggerGen DescribeAllParametersInCamelCase() which turns all the parameters into camelCase.

Is there DescribeAllParametersInPascalCase() method?

How can I configure Swagger/Swashbuckle to show input/output parameters in PascalCase?

Here's an example:

enter image description here

Grubstake answered 24/4, 2020 at 9:57 Comment(0)
S
13

You can configure the JsonSerializerOptions like this:

.AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null)

Example:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers()
.AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null);
Sheared answered 24/4, 2020 at 22:40 Comment(6)
Worked like a charm.Grubstake
I wanted camel casing and didn't want to rely on any "defaults", so instead setting this to null, I set it to System.Text.Json.JsonNamingPolicy.CamelCase.Diactinic
Where do I put this? On which object do I call .AddJsonOptions?Mckown
To AddController().AddJsonOptions()Grubstake
Works good for property names, not for dictionary keys though 😔. You can also set JsonSerializerOptions.DictionaryKeyPolicy = null; but it only works for the actual response, not for the example generated by SwaggerGen.Rightwards
it does not fix the problemCrispy
K
7

If you are still using Newtonsoft.Json in Asp.Net Core 3.1 instead of the new defualt System.Text.Json.

Once you configure Newtonsoft for Asp.Net Core 3.1 by:

services.AddControllers().AddNewtonsoftJson(x => {
  // My config is Pascal Case
  x.SerializerSettings.ContractResolver = new DefaultContractResolver();
});

You need to also install Swashbuckle.AspNetCore.Newtonsoft and opt in by adding the following after services.AddSwaggerGen(... :

services.AddSwaggerGenNewtonsoftSupport();
Kierakieran answered 23/3, 2021 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.