天天看點

swagger上傳檔案并支援jwt認證

swagger上傳檔案并支援jwt認證

背景

  由于swagger不僅提供了自動實作接口文檔的說明而且支援頁面調試,告别postman等工具,無需開發人員手動寫api文檔,縮減開發成本得到大家廣泛認可

但是由于swagger沒有提供上傳檔案的支援,是以隻能靠開發人員自己實作。今天就來看看如何擴充swagger達到上傳檔案的需求

動起小手手

 1安裝swagger

nuget安裝Swashbuckle.AspNetCore.Swagger元件

2設定生成xml

右鍵項目>屬性>生成

swagger上傳檔案并支援jwt認證

相應的把其他需要生成文檔說明的項目也按上步驟進行設定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 = "[email protected]", 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"
                });
            }
        }
    }
}      
swagger上傳檔案并支援jwt認證
swagger上傳檔案并支援jwt認證

打開浏覽器http://localhost:8532/docs/

swagger上傳檔案并支援jwt認證
swagger上傳檔案并支援jwt認證

還沒有結束,我們看看如何讓Jwt的認證資訊自動存在請求頭免去每次手動塞

點選

swagger上傳檔案并支援jwt認證
swagger上傳檔案并支援jwt認證

(實際情況是填寫的資訊格式是:Bearer *************(Bearer與後面資訊有一個空格))

 此時随意通路任何api,都會将以上資訊自動塞入header中進行請求,如下驗證

swagger上傳檔案并支援jwt認證

 至此目的都達到了

參考:

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

https://github.com/domaindrivendev/Swashbuckle

swagger上傳檔案并支援jwt認證

作者:Chaunce

來源:http://www.cnblogs.com/xiaoliangge/

GitHub:https://github.com/liuyl1992

個人位址:http://blog.chaunce.top

公衆号請搜:架構師進階俱樂部 SmartLife_com

swagger上傳檔案并支援jwt認證

聲明:原創部落格請在轉載時保留原文連結或者在文章開頭加上本人部落格位址,如發現錯誤,歡迎批評指正。凡是轉載于本人的文章,不能設定打賞功能等盈利行為

繼續閱讀