This is basically the same question as How do I set or remove the Default Response Content Type Using SwashBuckle, but for .NET Core 3.0
By default in .NET Core 3.0, you configure a web api with services.AddControllers()
and then you configure swagger with swashbuckle with services.AddSwaggerGen()
+ app.UseSwagger()
That is working fine, however the swagger.json contains multiple response content types for every operation (text/plain + application/json + text/json)
I know I can restrict these response content types by adding [Produces]
and [Consumes]
to my operations, but I'd like to avoid that for each and every operation (i.e I want to do that globally)
Please note that I preferably want to use System.Text.Json but if you have a solution that works only with Newtonsoft.JSON then it's better than nothing ;)
NSwag not only provides the functionality of Swashbuckle (Swagger generation) but also code generators. This way we can avoid incompatibilities and offer more features and a more streamlined toolchain.
AspNetCore. Swagger: a Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints. Swashbuckle. AspNetCore. SwaggerGen: a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models.
This attribute produces more descriptive response details for web API help pages generated by tools like Swagger. [ProducesResponseType] indicates the known types and HTTP status codes to be returned by the action.
The {documentName} refers to the name you specify in the AddSwaggerGen() method. The following code uses myapi as the name for a swagger document. builder.Services.AddSwaggerGen(options => options.SwaggerDoc("myapi", new OpenApiInfo { Title = "My API", Version = "v1" }) );
Swashbuckle.AspNetCore.SwaggerGen 5.0 uses the OpenApiOperation to describe API operations.
using System.Collections.Generic;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
public class AssignContentTypeFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Responses.ContainsKey("200"))
{
operation.Responses.Clear();
}
var data = new OpenApiResponse
{
Description = "Ok",
Content = new Dictionary<string, OpenApiMediaType>
{
["application/json"] = new OpenApiMediaType(),
["application/xml"] = new OpenApiMediaType(),
}
};
operation.Responses.Add("200", data);
}
}
In Startup.cs
services.AddSwaggerGen(q =>
{
q.SwaggerDoc("v1", new OpenApiInfo
{
Title = "mytitle",
Version = "v1",
});
q.OperationFilter<AssignContentTypeFilter>();
});
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