I recently upgraded a ASP.NET Core API application to Swashbuckle/Swagger 5.0.0 with ASP.NET Core 3.1.
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0" />
However, upon doing so I have noticed that the Swagger UI is now ignoring the Newtonsoft/JSON.NET JsonProperty attribute names on DTO properties. For example:
[HttpGet("testget", Name = "testget")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<TestGetResponse> TestGet()
{
var response = new TestGetResponse { MyName = "John" };
return Ok(response);
}
public class TestGetResponse
{
[JsonProperty("name")]
public string MyName { get; set; }
}
Is outputting in Swagger UI as:
Code 200: Example Value
Model
{
"myName": "string"
}
Instead of Model property name name
.
For Swagger in Startup.cs ConfigureServices I currently have:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "My API",
});
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
});
And for Swagger in Startup.cs Configure I currently have:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API");
c.RoutePrefix = "swagger";
});
I am aware that if I use the System.Text.Json
attribute JsonPropertyName
instead this will be fixed however I need to stick with the original attributes for now.
Is there a setting in Start.cs to tell SwaggerUI to use the Newtonsoft JsonProperty attribute or is there something I need to change at the ASP.NET Core level of configuration?
Using @JsonIgnore @JsonIgnore is a standard Jackson annotation. We can use it to specify that a field is to be ignored by Jackson during serialization and deserialization. We can add the annotation to just the field to be ignored, and it'll hide both getters and setters for the specified field.
How to do it? add this property in your Swagger UI Options defaultModelsExpandDepth: -1 for hide schema section and for more reference refer this swagger.io/docs/open-source-tools/swagger-ui/usage/… Can you please add your swagger ui configuration settings in your question.
It would appear that full support for NewtonSoft JSON.net from version 5.0.0 of Swashbuckle/Swagger is provided through a separate package.
To get this working:
1) Install the nuget package Swashbuckle.AspNetCore.Newtonsoft
version 5.0.0+
2) In Startup.ConfigureServices() make a call for the support:
services.AddSwaggerGenNewtonsoftSupport();
Further info can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With