#author("2024-01-17T22:16:34+08:00","default:Admin","Admin") #author("2024-01-18T23:58:25+08:00","default:Admin","Admin") [[ASP.NET Core Web]] &color(red){※This article is based on .NET Core2.2}; #contents * 配置 [#o6289a11] 默认的Swagger配置没有用户验证功能,需要配置一下,Swagger才能直接来测试API。 打开Program.cs,把builder.Services.AddSwaggerGen();这一句修改为: #codeprettify{{ 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”按钮 &color(red){※注意:填写的字符串的前面需要加上“Bearer ”}; * Tips [#bd7d825b] ** 上传文件 [#gc0b1a95] &color(red){ .net5.0 、swagger 5.6.3 环境下swagger上传文件的配置}; #codeprettify{{ 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" } } } } } } } }; } } } }} * Troubleshooting [#m028deb9] ** 不断提示:401 Undocumented Error [#a57276b9] 需要添加app.UseAuthentication(); 并且一定要在app.UseAuthorization();前面,顺序反了都不行 #codeprettify{{ app.UseAuthentication(); app.UseAuthorization(); }} ** Failed to load API definition [#cd55dbe0] 报出下面的错误 #codeprettify{{ Failed to load API definition }} 为了查看具体的错误信息 https://localhost:端口号/swagger/v1/swagger.json #codeprettify{{ 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即可。 #codeprettify{{ [ApiController] [Route("/")] public class HomeController : Controller { [HttpGet] public ResponseVm Index() { return ResponseVm.Success(); } } }} 解决方法② #codeprettify{{ builder.Services.AddSwaggerGen(options => { options.DocInclusionPredicate((name, api) => api.HttpMethod != null); }); }} #hr(); コメント: #comment_kcaptcha