简体   繁体   中英

How to implement Server Object in Swagger Document?

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?

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"
            }
        };
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM