Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate swagger.json from code with Swashbuckle V5

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 ?

like image 799
Call Me Audric Avatar asked Sep 17 '25 04:09

Call Me Audric


1 Answers

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.

like image 163
vernou Avatar answered Sep 19 '25 21:09

vernou