更新后似乎无法让 Swagger 工作 API

Can't seem to get Swagger to work after updating API

添加了几个 API 并更新了 lib 包后,我的 API 页面不再有效。在下面的堆栈跟踪中爆破的行是一个中间件。

这是堆栈跟踪:

[2020-06-23 23:35:40 Error] Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware
An unhandled exception has occurred while executing the request.
System.MissingMethodException: Method not found: 'Void Microsoft.OpenApi.Any.OpenApiString..ctor(System.String)'.
   at Swashbuckle.AspNetCore.SwaggerGen.OpenApiAnyFactory.CreateFor(OpenApiSchema schema, Object value)
   at Swashbuckle.AspNetCore.SwaggerGen.SchemaGenerator.ApplyParameterMetadata(OpenApiSchema schema, Type type, ParameterInfo parameterInfo)
   at Swashbuckle.AspNetCore.SwaggerGen.SchemaGenerator.GenerateSchema(Type type, SchemaRepository schemaRepository, MemberInfo memberInfo, ParameterInfo parameterInfo)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateParameter(ApiParameterDescription apiParameter, SchemaRepository schemaRepository)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.<>c__DisplayClass10_0.<GenerateParameters>b__1(ApiParameterDescription apiParam)
   at System.Linq.Enumerable.WhereSelectListIterator`2.ToList()
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateParameters(ApiDescription apiDescription, SchemaRepository schemaRespository)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperation(ApiDescription apiDescription, SchemaRepository schemaRepository)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
   at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at xxxxx.Api.Startup.<>c.<<Configure>b__8_0>d.MoveNext() in /Users/nicholaschen/Projects/xxxx/xxxx.Api/Startup.cs:line 352
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

这是启动代码块。

app.Use(async (context, next) =>
            {
                context.Response.GetTypedHeaders().CacheControl =
                    new CacheControlHeaderValue
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromDays(7) // Cloudflare's Certificate Transparency requirements.
                    };
                context.Response.Headers[HeaderNames.Vary] =
                    new[] {"Accept-Encoding"};

                await next();
            });

其中,await next();异常。也就是说,swagger json 要么没有生成,要么 swagger json 从未暴露在网络上。为什么?

Startup/ConfigureServices内的其他 DI 代码:

services.AddSwaggerGen(config =>
            {
                config.SwaggerDoc(GlobalApiVariables.CURRENT_API_VERSION, new OpenApiInfo
                {
                    Title = "XXXX API",
                    Version = GlobalApiVariables.CURRENT_API_VERSION,
                    Extensions = new Dictionary<string, IOpenApiExtension>
                    {
                        // Get the custom logo ready bitches
                        // 
                        {
                            "x-logo", new OpenApiObject
                            {
                                // TODO: Fix full routing
                                {"url", new OpenApiString("api-images/logo.svg")},
                                {"backgroundColor", new OpenApiString("#FFFFFF")},
                                {"altText", new OpenApiString("xxxx")}
                            }
                        }
                    }
                });

                // https://github.com/domaindrivendev/Swashbuckle.AspNetCore#swashbuckleaspnetcoreannotations
                config.EnableAnnotations(); // [SwaggerTag] support

                // Adds "(Auth)" to the summary so that you can see which endpoints have Authorization
                config.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                // or use the generic method, e.g. c.OperationFilter<AppendAuthorizeToSummaryOperationFilter<MyCustomAttribute>>();

                // [SwaggerRequestExample] & [SwaggerResponseExample]
                // version < 3.0 like this: c.OperationFilter<ExamplesOperationFilter>(); 
                // version 3.0 like this: c.AddSwaggerExamples(services.BuildServiceProvider());
                // version > 4.0 like this:
                config.ExampleFilters();
                config.OperationFilter<AddResponseHeadersFilter>(); // [SwaggerResponseHeader]

                // Locate the XML file being generated by .NET Core
                var filePath = Path.Combine(AppContext.BaseDirectory,
                    $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
                config.IncludeXmlComments(filePath);

                // Define the Api Key scheme that's in use (i.e. Implicit Flow)
                config.AddSecurityDefinition(ApiKeyAuthenticationOptions.DefaultScheme, new OpenApiSecurityScheme
                {
                    Description = "XXXX custom authorization header using the Api Key scheme. Example: \"{token}\"",
                    In = ParameterLocation.Header,
                    Name = ApiKeyAuthenticationOptions.HeaderKey,
                    Type = SecuritySchemeType.ApiKey,
                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri("/connect/validate", UriKind.Relative),
                            Scopes = new Dictionary<string, string>
                            {
                                {"readAccess", "Access read operations"},
                                {"writeAccess", "Access write operations"}
                            }
                        }
                    }
                });

                // add Security information to each operation for OAuth2
                config.OperationFilter<SecurityRequirementsOperationFilter>();

                config.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = ApiKeyAuthenticationOptions.DefaultScheme
                            }
                        },
                        new[] {"readAccess", "writeAccess"}
                    }
                });
            });
            services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()
            services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

Startup/Configure内的其他 DI 代码:

app.UseSwagger(c =>
            {
                c.RouteTemplate = "/{documentName}/swagger.json";
                c.SerializeAsV2 = true;
            });

app.UseReDoc(c =>
            {
                c.DocumentTitle = "XXX API";
                c.RoutePrefix = "";
                c.SpecUrl($"/{GlobalApiVariables.CURRENT_API_VERSION}/swagger.json");
                c.ConfigObject = new ConfigObject
                {
                    HideDownloadButton = true,
                    HideLoading = true
                };
                c.NativeScrollbars();
                // c.OAuthClientSecret(ApiKeyAuthenticationOptions.HeaderKey);
            });

如果您想查看我的软件包版本:

.NET 核心 SDK 3.1.301

OpenApi 打破了这个。暂时不要更新您的软件包。

https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters/issues/154