swagger上傳文件並支持jwt認證

背景

  因爲swagger不只提供了自動實現接口文檔的說明並且支持頁面調試,告別postman等工具,無需開發人員手動寫api文檔,縮減開發成本獲得你們普遍承認css

可是因爲swagger沒有提供上傳文件的支持,因此只能靠開發人員本身實現。今天就來看看如何擴展swagger達到上傳文件的需求html

動起小手手

 1安裝swagger

nuget安裝Swashbuckle.AspNetCore.Swagger組件git

2設置生成xml

右鍵項目>屬性>生成github

相應的把其餘須要生成文檔說明的項目也按上步驟進行設置xmlweb

關鍵swagger代碼json

複製代碼
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過濾器api

複製代碼
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的認證信息自動存在請求頭免去每次手動塞安全

點擊app

 

(實際狀況是填寫的信息格式是:Bearer *************(Bearer與後面信息有一個空格))

 此時隨意訪問任何api,都會將以上信息自動塞入header中進行請求,以下驗證

 

 至此目的都達到了

參考:

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

https://github.com/domaindrivendev/Swashbuckle

相關文章
相關標籤/搜索