[英]SWAGGER UI does not show up - Swagger.json does on .NET Core
當我點擊 http://localhost:5000/swagger/index.html 時,SWAGGER UI 不顯示,而我可以在 http://localhost:5000/swagger/v1/swagger.json 訪問 Swagger.json
即
這是我的program.cs中的內容
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
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>()
}
});
});
}
其中ConfigureSwaggerOptions在下面
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 導入郵遞員。 但是,招搖的 UI 沒有出現。
我已經在 .Net5 和 .Net core2.1 項目中測試了你的方法,它工作正常。
提示:請把 env.IsDevelopment 的 swagger 語句改成 outsite。 這是很容易被忽視的地方。
.Net 5.0
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using webapi.Middleware;
using System.Reflection;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
namespace webapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddApplicationInsightsTelemetry();
services.AddLogging();
services.AddControllers().AddNewtonsoftJson();
services.AddApiVersioning(
options =>
{
// reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
options.ReportApiVersions = true;
});
services.AddVersionedApiExplorer(
options =>
{
// add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
// note: the specified format code will format the version as "'v'major[.minor][-status]"
options.GroupNameFormat = "'v'VVV";
// note: this option is only necessary when versioning by url segment. the SubstitutionFormat
// can also be used to control the format of the API version in route templates
options.SubstituteApiVersionInUrl = true;
});
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>()
}
});
});
}
services.AddDistributedMemoryCache();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
IApiVersionDescriptionProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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());
}
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//app.UseCustomMiddleware();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
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;
}
}
}
.Net 2.1
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Swagger21
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddApplicationInsightsTelemetry();
services.AddLogging();
services.AddMvcCore().AddVersionedApiExplorer();
services.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1, 0);
});
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>()
}
});
});
}
services.AddDistributedMemoryCache();
services.AddSession();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app , IHostingEnvironment env,
IApiVersionDescriptionProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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());
}
});
app.UseHttpsRedirection();
app.UseSession();
app.UseMvc();
}
}
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;
}
}
}
你不見了
app.UseSwagger();
app.UseSwaggerUI();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.