我正在启动一个新的Core
Web API,并想将Swagger
添加到我的应用程序中。
我当前的环境:
这是我的Startup.cs
类和配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//AK: Enable CORS
//CORS should be configured on host server.
services.AddCors(setupAction =>
{
setupAction.AddPolicy(DevCorsPolicyName,
builder =>
{
builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
});
});
#region Configuration
//Configuration File
services.Configure<AppSettingConfiguration>(Configuration.GetSection("AppSettings"));
//AutoMapper
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
//Configure Swagger
services.ConfigureSwaggerGen(c =>
{
c.SwaggerDoc("v3", new OpenApiInfo
{
Title = "GTrackAPI",
Version = "v3"
});
});
#endregion
#region Dependency Injection
//Database context and repository
services.AddDbContext<IGTrackContext, GTrackContext>(builder =>
{
builder.UseSqlServer(connectionString: Configuration.GetConnectionString("gtrackConnection"), sqlServerOptionsAction: null);
});
services.AddScoped<IGTrackRepository, GTrackRepository>();
//facade layers
services.AddScoped<IPersonFacade, PersonFacade>();
//Service layers
services.AddScoped<IPersonService, PersonService>();
#endregion
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//Enable development environment only settings
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//AK: Only allow all origins for development environmnet
app.UseCors(DevCorsPolicyName);
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "GTrackAPI");
c.RoutePrefix = string.Empty; //Configures swagger to load at application root
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
运行应用程序时,出现以下错误:
InvalidOperationException:尝试调用中间件“ Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware”时,无法解析“ Swashbuckle.AspNetCore.Swagger.ISwaggerProvider”类型的服务。
这里是Stacktrace
:
System.InvalidOperationException:尝试调用中间件“ Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware”时,无法解析“ Swashbuckle.AspNetCore.Swagger.ISwaggerProvider”类型的服务。 在Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.GetService(IServiceProvider sp,Type type,Type middleware) 在lambda_method(Closure,Object,HttpContext,IServiceProvider) 在Microsoft.AspNetCore.Builder.UseMiddlewareExtensions。<> c__DisplayClass4_1.b__2(HttpContext上下文) 在Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext上下文,ICorsPolicyProvider corsPolicyProvider) 在Microsoft.AspNetCore.Builder.UseMiddlewareExtensions。<> c__DisplayClass4_1.b__2(HttpContext上下文) 在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)
很明显,我在这里遗漏了一些东西,不确定到底是什么。任何帮助将不胜感激。
答案 0 :(得分:1)
致电
services.AddSwaggerGen();
在ConfigureServices
中似乎丢失了。
public static IServiceCollection AddSwaggerGen(
this IServiceCollection services,
Action<SwaggerGenOptions> setupAction = null)
{
// Add Mvc convention to ensure ApiExplorer is enabled for all actions
services.Configure<MvcOptions>(c =>
c.Conventions.Add(new SwaggerApplicationConvention()));
// Register generator and it's dependencies
services.AddTransient<ISwaggerProvider, SwaggerGenerator>();
services.AddTransient<ISchemaGenerator, SchemaGenerator>();
services.AddTransient<IApiModelResolver, JsonApiModelResolver>();
// Register custom configurators that assign values from SwaggerGenOptions (i.e. high level config)
// to the service-specific options (i.e. lower-level config)
services.AddTransient<IConfigureOptions<SwaggerGeneratorOptions>, ConfigureSwaggerGeneratorOptions>();
services.AddTransient<IConfigureOptions<SchemaGeneratorOptions>, ConfigureSchemaGeneratorOptions>();
// Used by the <c>dotnet-getdocument</c> tool from the Microsoft.Extensions.ApiDescription.Server package.
services.TryAddSingleton<IDocumentProvider, DocumentProvider>();
if (setupAction != null) services.ConfigureSwaggerGen(setupAction);
return services;
}
这就是将ISwaggerProvider
添加到服务集合的原因
您可以将当前代码重构为
//...
//Configure Swagger
services.AddSwaggerGen(c => { //<-- NOTE 'Add' instead of 'Configure'
c.SwaggerDoc("v3", new OpenApiInfo {
Title = "GTrackAPI",
Version = "v3"
});
});
//...
如源代码所示,它最终将通过设置操作调用ConfigureSwaggerGen
。
答案 1 :(得分:0)
如果您使用 dotnet CLI 创建了 Web API asp dotnet 应用程序,并且您收到此错误 错误 NU1100:无法解析“net5.0”的“Swashbuckle.AspNetCore (>= 5.6.3)”
这意味着 dotnet CLI 无法找到 swagger 依赖
要解决此问题,您可以运行以下 dotnet CLI 命令
dotnet add package Swashbuckle.AspNetCore.Swagger --version 5.6.3