swagger上传文件并支持jwt认证

背景

  由于swagger不仅提供了自动实现接口文档的说明而且支持页面调试,告别postman等工具,无需开发人员手动写api文档,缩减开发成本得到大家广泛认可

但是由于swagger没有提供上传文件的支持,所以只能靠开发人员自己实现。今天就来看看如何扩展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中进行请求,如下验证

 

 至此目的都达到了

参考:

http://www.cnblogs.com/Erik_Xu/p/8904854.html#3961244

https://github.com/domaindrivendev/Swashbuckle

 

posted @ 2018-05-14 15:23  Leon_Chaunce  阅读(4329)  评论(10编辑  收藏  举报