I was using Swashbuckle AspNetCore v4.x.x and I upgrade to the v5.1.x.x. But the code I used in not working anymore, because of the lack of the class "SwaggerContractResolver".
The goal I attempt to is to generate the swagger.json in code of my RESTfull API :
public static string GenerateSwagger(this IWebHost webhost, string docName, string basePath)
{
var sw = (ISwaggerProvider)webhost.Services.GetService(typeof(ISwaggerProvider));
var doc = sw.GetSwagger(docName, null, basePath);
var json = JsonConvert.SerializeObject(
doc,
Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new SwaggerContractResolver(new JsonSerializerSettings())
}
);
return json;
}
string json = GenerateSwagger(webhost, docName, url);
string path = Path.Combine(path, docName);
File.WriteAllText(path + ".json", json);
How can I do to do this working like the v4 but with the new version of Swashbuckle AspnetCore ?
With Swashbuckle V5, you can use .NET Core CLI to generate the swagger contract :
https://github.com/domaindrivendev/Swashbuckle.AspNetCore#swashbuckleaspnetcorecli
But this work only with .NET Core API. For .NET Framework, you can use this method :
public static string GenerateSwagger(this IWebHost webhost, string docName, string basePath)
{
var sw = webhost.Services.GetRequiredService<ISwaggerProvider>();
var doc = sw.GetSwagger(docName, null, basePath);
using (var streamWriter = new StringWriter())
{
var writer = new OpenApiJsonWriter(streamWriter);
doc.SerializeAsV3(writer);
return streamWriter.ToString();
}
}
You can witch OpenApiJsonWriter
to OpenApiYamlWriter
if you want YAML swagger contract.
You can switch SerializeAsV3
to SerializeAsV2
if you want V2 swagger contract.
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