这篇文章将为大家详细讲解有关如何使用swagger上传文件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
1安装swagger
nuget安装Swashbuckle.AspNetCore.Swagger组件
2设置生成xml
右键项目>属性>生成
相应的把其他需要生成文档说明的项目也按上步骤进行设置xml
关键swagger代码
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.PlatformAbstractions; using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Chaunce.Api.App_Start { /// <summary> /// SwaggerConfig /// </summary> public class SwaggerConfig { /// <summary> /// InitSwagger /// </summary> /// <param name="services"></param> public static void InitSwagger(IServiceCollection services) { services.AddSwaggerGen(c => { c.OperationFilter<SwaggerFileUploadFilter>();//增加文件过滤处理 var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, }; c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。 var basePath = PlatformServices.Default.Application.ApplicationBasePath;// 获取到应用程序的根路径 var xmlApiPath = Path.Combine(basePath, "Chaunce.Api.xml");//api文件xml(在以上步骤2设置生成xml的路径) var xmlModelPath = Path.Combine(basePath, "Chaunce.ViewModels.xml");//请求modelxml c.IncludeXmlComments(xmlApiPath); c.IncludeXmlComments(xmlModelPath); c.SwaggerDoc("v1", new Info { Title = "Chaunce数据接口", Version = "v1", Description = "这是一个webapi接口文档说明", TermsOfService = "None", Contact = new Contact { Name = "Chaunce官网", Email = "info@Chaunce.com", Url = "http://blog.Chaunce.top/" }, License = new License { Name = "Swagger官网", Url = "http://swagger.io/", } }); c.IgnoreObsoleteActions(); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "权限认证(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"", Name = "Authorization",//jwt默认的参数名称 In = "header",//jwt默认存放Authorization信息的位置(请求头中) Type = "apiKey" });//Authorization的设置 }); } /// <summary> /// ConfigureSwagger /// </summary> /// <param name="app"></param> public static void ConfigureSwagger(IApplicationBuilder app) { app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwagger(c => { c.RouteTemplate = "docs/{documentName}/docs.json";//使中间件服务生成Swagger作为JSON端点(此处设置是生成接口文档信息,可以理解为老技术中的webservice的soap协议的信息,暴露出接口信息的地方) c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Info.Description = httpReq.Path);//请求过滤处理 }); app.UseSwaggerUI(c => { c.RoutePrefix = "docs";//设置文档首页根路径 c.SwaggerEndpoint("/docs/v1/docs.json", "V1");//此处配置要和UseSwagger的RouteTemplate匹配 //c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1");//默认终结点 c.InjectStylesheet("/swagger-ui/custom.css");//注入style文件 }); } } }
swagger过滤器
using Microsoft.AspNetCore.Http; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Chaunce.Api.Help { /// <summary> /// swagger文件过滤器 /// </summary> public class SwaggerFileUploadFilter : IOperationFilter { /// <summary> /// swagger过滤器(此处的Apply会被swagger的每个接口都调用生成文档说明,所以在此处可以对每一个接口进行过滤操作) /// </summary> /// <param name="operation"></param> /// <param name="context"></param> public void Apply(Operation operation, OperationFilterContext context) { if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) && !context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase)) { return; } var apiDescription = context.ApiDescription; var parameters = context.ApiDescription.ParameterDescriptions.Where(n => n.Type == typeof(IFormFileCollection) || n.Type == typeof(IFormFile)).ToList();//parameterDescriptions包含了每个接口所带所有参数信息 if (parameters.Count() <= 0) { return; } operation.Consumes.Add("multipart/form-data"); foreach (var fileParameter in parameters) { var parameter = operation.Parameters.Single(n => n.Name == fileParameter.Name); operation.Parameters.Remove(parameter); operation.Parameters.Add(new NonBodyParameter { Name = parameter.Name, In = "formData", Description = parameter.Description, Required = parameter.Required, Type = "file", //CollectionFormat = "multi" }); } } } }
打开浏览器http://localhost:8532/docs/
还没有结束,我们看看如何让Jwt的认证信息自动存在请求头免去每次手动塞
点击
(实际情况是填写的信息格式是:Bearer *************(Bearer与后面信息有一个空格))
此时随意访问任何api,都会将以上信息自动塞入header中进行请求,如下验证
关于如何使用swagger上传文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。