简体   繁体   中英

api version value by default in swagger-ui

I have configure swagger in our asp.core wep-api project and its working perfectly fine.Now i am looking into solution when swagger-ui appears as shown below

https://imgur.com/a/K7QTKCu

the api version part should be fill automatically as per configuration from code side.

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "My API",
                Contact = new Contact
                {
                    Name = "My Api",
                    Url = "https://109.com/"
                }
            });
            var security = new Dictionary<string, IEnumerable<string>>
            {
                {"Bearer", new string[] { }},
            };
            c.AddSecurityDefinition("Bearer", new ApiKeyScheme
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = "header",
                Type = "apiKey"
            });
            c.AddSecurityRequirement(security);
        });

You need to install Microsoft.AspNetCore.Mvc.Versioning and Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer packages to enable the API versioning in Swagger.

You can check the additional details at here .

In ConfigureServices method define the versioning scheme as

 services.AddVersionedApiExplorer(o =>
 {
      o.GroupNameFormat = "'v'VVV";
      o.SubstituteApiVersionInUrl = true;
 });
 services.AddApiVersioning(config =>
 {
     config.DefaultApiVersion = new ApiVersion(1, 0);
     config.AssumeDefaultVersionWhenUnspecified = true;
     config.ReportApiVersions = true;
 });

You need to add options.SubstituteApiVersionInUrl=true to tell swagger to replace the version in the controller route and configure the api version:

services.AddApiVersioning(options => options.ReportApiVersions = true);
services.AddMvcCore()
    .AddJsonFormatters()
    .AddVersionedApiExplorer(
          options =>
          {
              ////The format of the version added to the route URL  
              options.GroupNameFormat = "'v'VVV";
              //Tells swagger to replace the version in the controller route  
              options.SubstituteApiVersionInUrl = true;
          });

Also you need to add this to your controller:

[Route("api/[controller]")]
[ApiVersion("1.0")]
[ApiController]

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