当我点击http://localhost:5000/swagger/index.html时,SWAGGER用户界面没有显示,而我可以通过http://localhost:5000/swagger/v1/swagger.json访问Swagger.json
即
下面是我的程序中的内容。cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
启动.cs -配置
app.UseSwagger();
app.UseSwaggerUI(c =>
{
foreach (var description in provider.ApiVersionDescriptions.OrderByDescending(o => o.GroupName))
{
c.SwaggerEndpoint(
$"/swagger/{description.GroupName}/swagger.json",
description.GroupName.ToUpperInvariant());
}
});
和Startup.cs -配置服务
//Swagger Services.
services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
if (this.Configuration["EnableSwagger"] == "true")
{
//services.AddSwaggerGen(opt =>
//opt.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
//// Set the comments path for the Swagger JSON and UI.
//var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
//var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
//opt.IncludeXmlComments(xmlPath);
services.AddSwaggerGen(opt =>
{
opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme."
});
opt.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
}
下面是配置SwaggerOptions
public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions>
{
readonly IApiVersionDescriptionProvider _apiVerProvider;
public ConfigureSwaggerOptions(IApiVersionDescriptionProvider apiVerProvider) => _apiVerProvider = apiVerProvider;
public void Configure(SwaggerGenOptions options)
{
foreach (var description in _apiVerProvider.ApiVersionDescriptions)
{
options.SwaggerDoc(description.GroupName, GetSwaggerDocInfo(description));
}
}
static OpenApiInfo GetSwaggerDocInfo(ApiVersionDescription description)
{
var info = new OpenApiInfo
{
Title = $"WebAPI {description.ApiVersion}",
Version = description.GroupName,
Description = "Web API Template",
Contact = new OpenApiContact()
{
Name = "Web API service"
},
License = new OpenApiLicense()
{
Name = "MIT"
}
};
if (description.IsDeprecated)
{
info.Description += $" {description.ApiVersion} API version is deprecated.";
}
return info;
}
}
我可以将swagger.json导入到postman中,但是swagger UI没有显示出来。
2条答案
按热度按时间toiithl61#
我已经在.Net5和.Net core2.1项目中测试了你的方法,它工作得很好。
提示:* 请将“env.isdevelopment”中的“swagger”语句改为“outsite”。* 这是容易被忽略的地方。
.网络版5.0
.网络版2.1
vecaoik12#
你失踪了