Reputation: 9119
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?
Upvotes: 17
Views: 12984
Reputation: 9119
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.
Upvotes: 49