Search code examples
c#.net-coreswagger.net-6.0swashbuckle.aspnetcore

.net 6.0 : How to generate Swagger.json file on build in .net 6.0?


I want to generate Swagger.Json file on build and use it in API gateway to configure the endpoints.

I have tried following steps but its not working.

Create a tool manifest:

dotnet new tool-manifest

Install the Swashbuckle CLI tool and add it to the local manifest file: But this step fails

dotnet tool install --version 6.4.0 Swashbuckle.AspNetCore.Cli

Error :

 NU1202: Package Swashbuckle.AspNetCore.Cli 6.4.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0). Package Swashbuckle.AspNetCore.Cli 6.4.0 supports:
  - net5.0 (.NETCoreApp,Version=v5.0) / any
  - net6.0 (.NETCoreApp,Version=v6.0) / any
  - netcoreapp2.1 (.NETCoreApp,Version=v2.1) / any
  - netcoreapp3.0 (.NETCoreApp,Version=v3.0) / any
NU1212: Invalid project-package combination for Swashbuckle.AspNetCore.Cli 6.4.0. DotnetToolReference project style can only contain references of the DotnetTool type 
NU1212: Invalid project-package combination for Swashbuckle.AspNetCore.Cli 6.4.0. DotnetToolReference project style can only contain references of the DotnetTool type 
Package 'Swashbuckle.AspNetCore.Cli 6.4.0' has a package type 'DotnetTool' that is not supported by project 'WebApi'.

Solution

  • UPDATED: Generate Swagger JSON File: A Method Using CLI without the Necessity to Debug or Run the App for Generation--

    A. (optional) In the API project properties, (1) enable the documentation file, and (2) specify the output XML filename and path.

    enter image description here

    Source: Adding Swagger to ASP.NET Core Web API Using XML Documentation

    Include the on-build generated file in the Swagger configuration to make all documentation references appear in the Swagger UI.

    enter image description here

    B. Run the following commands to enable on-build Swagger JSON config file generation and set the path to the Web API project:

    dotnet new tool-manifest

    dotnet tool install --version 5.3.1 Swashbuckle.AspNetCore.Cli

    the version is optional and should be compatible with the current installed swagger libs

    Source: How to Generate a Swagger JSON File on Build in .NET Core

    C. To test JSON config file generation, run the following command:

    dotnet swagger tofile --output swagger.json "bin\debug\net7.0\APIs.dll" v1

    • the APIs.dll here is the produced dll of the API project
    • v1 here is the document name defined in config.SwaggerDoc("v1"...

    D. (optional) You can automate the operation using build events e.g. post build event or by executing commands as background action programmatically.

     public class AutoSwaggeFileGeneratorMiddleware
    {
        private Process GenerateProcess()
        {
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
    
            return new Process { StartInfo = startInfo };
        }
    
        private async Task ConsumeStreamReaderAsync(StreamReader reader, string prefix)
        {
            string line;
            while ((line = await reader.ReadLineAsync()) != null)
            {
                if (prefix.ToLower().Contains("error"))
                    _logger.LogError($"{prefix}{line}"); // Log to the ILogger
                else
                    _logger.LogInformation($"{prefix}{line}"); // Log to the ILogger
            }
        }
    
        public async Task Invoke(HttpContext context)
        {
            using (Process process = GenerateProcess())
            {
                string command = "dotnet swagger tofile --output swagger.json "bin\debug\net7.0\APIs.dll" v1";
                process.Start();
    
                // Send the AutoRest CLI command to the standard input of the process
                using (StreamWriter sw = process.StandardInput)
                {
                    if (sw.BaseStream.CanWrite)
                    {
                        await sw.WriteLineAsync(command);
                    }
                }
    
                // Do not wait for the process to exit, and let it run in the background
    
                // Handle the output and error streams asynchronously
                var outputTask = ConsumeStreamReaderAsync(process.StandardOutput, "Output: ");
                var errorTask = ConsumeStreamReaderAsync(process.StandardError, "Error: ");
    
                // Continue processing other requests while the batch file is running
                Task.WhenAll(outputTask, errorTask);
            }
        }
    }
    

    Do NOT forget to use it in Middleware app.UseMiddleware<AutoRestMiddleware>();


    OLD ANSWER

    Check below practice The idea works in requesting the swagger.json on execution.

    https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/541#issuecomment-358772489

    enter image description here

    There is also another solution using the build-time, instead.