※This article is based on .NET Core2.2
默认的Swagger配置没有用户验证功能,需要配置一下,Swagger才能直接来测试API。
打开Program.cs,把builder.Services.AddSwaggerGen();这一句修改为:
builder.Services.AddSwaggerGen(c => { c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Description = "Bearer Token", Name = "Authorization", BearerFormat = "JWT", Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme() { Reference=new OpenApiReference() { Type=ReferenceType.SecurityScheme, Id="Bearer" } },new string[]{ } } }); });
右上角会出现“Authorize”按钮
※注意:填写的字符串的前面需要加上“Bearer ”
.net5.0 、swagger 5.6.3 环境下swagger上传文件的配置
using Microsoft.AspNetCore.Http; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections.Generic; using System.Linq; namespace SProj.Filters { public class SwaggerFileUploadFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) && !context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase)) { return; } var fileParameters = context.ApiDescription.ActionDescriptor.Parameters.Where(n => n.ParameterType == typeof(IFormFile)).ToList(); if (fileParameters.Count < 0) { return; } operation.RequestBody = new OpenApiRequestBody { Description = "upload file ", Content = new Dictionary<String, OpenApiMediaType> { { "multipart/form-data", new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Required = new HashSet<String>{ "file" }, Properties = new Dictionary<String, OpenApiSchema> { { "file", new OpenApiSchema() { Type = "string", Format = "binary" } } } } } } } }; } } }
报出下面的错误
Failed to load API definition
为了查看具体的错误信息
https://localhost:端口号/swagger/v1/swagger.json
An unhandled exception occurred while processing the request. SwaggerGeneratorException: Ambiguous HTTP method for action - SINOData.Controllers.OrderController.Success (SINOData). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0 Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository) Stack Query Cookies Headers Routing SwaggerGeneratorException: Ambiguous HTTP method for action - SINOData.Controllers.OrderController.Success (SINOData). Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0 Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GenerateOperations(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository) Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable<ApiDescription> apiDescriptions, SchemaRepository schemaRepository) Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(string documentName, string host, string basePath) Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
看报错得知 action HomeController.Index 未明确标记 HttpMethod,这个action可以访问是因为全局路由所以可以访问。看到这个报错直接在报错对应的action上增加HttpMethod即可。
[ApiController] [Route("/")] public class HomeController : Controller { [HttpGet] public ResponseVm Index() { return ResponseVm.Success(); } }
コメント: