How to implement Server Object in Swagger Document?

Viewed 364

I am new in swagger. My requirement is to add server objects in swagger json. Following is a sample servers object:

servers:
- url: https://api.openweathermap.org/data/2.5/

Do we need to configure something to the AddSwaggerGen() in startup.cs file for achieving this?

Or is there any configuration options to set server URL and where we can specify multiple server URLs for different environments?

1 Answers

You need to do it when configuring the Swagger middleware with UseSwagger method like below:

app.UseSwagger(options =>
{
    options.PreSerializeFilters.Add((swagger, httpReq) =>
    {
        swagger.Servers = new List<OpenApiServer>
        {
            // You can add as many OpenApiServer instances as you want by creating them like below
            new OpenApiServer
            {
                // You can set the Url from the default http request data or by hard coding it
                // Url = $"{httpReq.Scheme}://{httpReq.Host.Value}",
                Url = "https://api.openweathermap.org/data/2.5", 
                Description = "Open Weather Map"
            }
        };
    });
});
Related