Search code examples
c#asp.net-web-apiswaggerswashbuckleswagger-codegen

How to add host variable in swagger json file at C#


I have a C# asp.net project based on .NET 6 and I want to generate swagger json file to implement client based on this file

In this situation I need to specify host variable to determine client how to connect server.

But my question is how to do this?


Solution

  • You can use below code to add host variable into the json file

                // Add host to generated swagger file (swagger.json)
                options.AddServer(new OpenApiServer {
                    Url = "http://{serverAddress}",
                    Description = "IpTables Test Server",
                    Variables = new Dictionary<string, OpenApiServerVariable>
                    {
                        { "serverAddress", new OpenApiServerVariable {
                                                    Default = "192.168.21.56:8080",
                                                    Description = "Target Server Address" }
                        }
                    }
                });
    

    this options is for SwaggerGenOptions and you can set this in program.cs or startup.cs typically.