.Net WebApi接口之Swagger集成詳解

本文詳細的介紹了.net從一個新的項目中建立api後集成swagger調試接口的流程!html

一、首先咱們建立一個MVC項目(VS2012):node

二、而後在項目中的Controllers文件夾中添加API接口文件(WebApi):web

 

建立以後,接口中隨便寫一個獲取信息的方法:ajax

  

   

三、集成swagger,經過nuget管理平臺添加(右鍵網站項目-->管理NuGet程序包):json

在打開的NuGet包程序管理界面,聯機輸入:Swashbuckle 搜索。api

 

在打開的NuGet包程序管理界面,聯機輸入:swagger 搜索。瀏覽器

 

在打開的NuGet包程序管理界面,聯機輸入:WebActivatorEx 搜索。服務器

 

安裝以後在App_Start文件夾下會自動生成的swagger配置文件SwaggerConfig.cs:架構

 

四、安裝以後還無法正常訪問swagger,須要配置網站屬性:app

 
修改自動生成的SwaggerConfig文件

 

  

注意配置生成的xml文檔位置(swagger接口註釋用的): 

c.IncludeXmlComments(string.Format("{0}/Doc/CYP.GMS.CooperativeBusiness.WebService.XML", System.AppDomain.CurrentDomain.BaseDirectory));
c.IncludeXmlComments(string.Format("{0}/Doc/CYP.GMS.CooperativeBusiness.Model.XML", System.AppDomain.CurrentDomain.BaseDirectory));

也能夠自定義一個獨立方法來配置:

c.IncludeXmlComments(GetXmlCommentsPath);

protected static string GetXmlCommentsPath()

{
        var xmlPath = System.String.Format(@"{0}/Doc/CYP.GMS.CooperativeBusiness.WebService.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        return xmlPath ;
 }

注:這裏的XML路徑和文件名稱必須與網站生成的XMl名稱一致。

而且須要再WebApiConfig.cs配置中添加  config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

 
 

五、大功告成:在瀏覽器中輸入以下地址:http://localhost:17420/swagger,顯示以下頁面:

點擊相應的服務,在顯示的框中輸入對應的信息,再點擊「Try it out!」,便可成功調用服務,並可查看返回的結果。

Swagger的一些高級用法

   Swagger很是強大,不單單是一些幫助頁面信息,還能夠進行api的調試。這樣就能夠不用藉助第三方工具 如:postman,進行webapi的調試。swagger通過配置,還能夠輸入一些http頭部信息,如權限認證信息等。下面就來說解如下具體的配置。

   首先咱們須要新建一個類 HttpHeaderOperation,讓該類繼承IOperationFilter 接口,該接口需引入命名空間:Swashbuckle.AspNetCore.SwaggerGen,實現接口方法Apply 代碼以下:     

public class HttpHeaderOperation : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (operation.Parameters == null) { operation.Parameters = new List<IParameter>(); } var actionAttrs = context.ApiDescription.ActionAttributes(); var isAuthorized= actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); if (isAuthorized == false) //提供action都沒有權限特性標記,檢查控制器有沒有
 { var controllerAttrs= context.ApiDescription.ControllerAttributes(); isAuthorized= controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); } var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); if (isAuthorized && isAllowAnonymous == false) { operation.Parameters.Add(new NonBodyParameter() { Name = "Authorization",  //添加Authorization頭部參數
                    In = "header", Type = "string", Required = false }); } } }

  而後在 Startup.cs 中的 ConfigureServices 方法,找到以前的AddSwaggerGen 代碼段,在最後添加以下代碼:

c.OperationFilter<HttpHeaderOperation>() services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "TwBusManagement接口文檔", Description = "RESTful API for TwBusManagement", TermsOfService = "None", Contact = new Contact { Name = "Alvin_Su", Email = "alvin_su@outlook.com", Url = "" } }); //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "twbusapi.xml"); c.IncludeXmlComments(xmlPath); c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader參數
            });

  這樣,咱們容許webapi項目後,就能夠輸入 Authorization 頭部參數了。以下圖:

  

 控制器上的註釋顯示設置

1.定義一個provider實現ISwaggerProvider接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Swashbuckle.Swagger;
using System.Collections.Concurrent;
using System.IO;
using System.Xml;

namespace Project.Example.Web.App_Start
{
    /// <summary>
    /// Swagger顯示控制器的描述
    /// </summary>
    public class SwaggerControllerDescProvider : ISwaggerProvider
    {
        private readonly ISwaggerProvider _swaggerProvider;
        private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
        private readonly string _xml;
        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="swaggerProvider"></param>
        /// <param name="xml">xml文檔路徑</param>
        public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
        {
            _swaggerProvider = swaggerProvider;
            _xml = xml;
        }

        /// <summary>
        /// 獲取SwaggerDocument
        /// </summary>
        /// <param name="rootUrl"></param>
        /// <param name="apiVersion"></param>
        /// <returns></returns>
        public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
        {
            var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
            SwaggerDocument srcDoc = null;
            //只讀取一次
            if (!_cache.TryGetValue(cacheKey, out srcDoc))
            {
                srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);

                srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
                _cache.TryAdd(cacheKey, srcDoc);
            }
            return srcDoc;
        }

        /// <summary>
        /// 從API文檔中讀取控制器描述
        /// </summary>
        /// <returns>全部控制器描述</returns>
        public ConcurrentDictionary<string, string> GetControllerDesc()
        {
            string xmlpath = _xml;
            ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
            if (File.Exists(xmlpath))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(xmlpath);
                string type = string.Empty, path = string.Empty, controllerName = string.Empty;

                string[] arrPath;
                int length = -1, cCount = "Controller".Length;
                XmlNode summaryNode = null;
                foreach (XmlNode node in xmldoc.SelectNodes("//member"))
                {
                    type = node.Attributes["name"].Value;
                    if (type.StartsWith("T:"))
                    {
                        //控制器
                        arrPath = type.Split('.');
                        length = arrPath.Length;
                        controllerName = arrPath[length - 1];
                        if (controllerName.EndsWith("Controller"))
                        {
                            //獲取控制器註釋
                            summaryNode = node.SelectSingleNode("summary");
                            string key = controllerName.Remove(controllerName.Length - cCount, cCount);
                            if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
                            {
                                controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
                            }
                        }
                    }
                }
            }
            return controllerDescDict;
        }
    }
}

2.定義一個JS文件, 修改屬性設置成嵌入資源,這個js文件的功能主要有兩個,一個是漢化,另外一個就是在界面上顯示控制器的描述文字

 Swagger-Custom.js

'use strict';
window.SwaggerTranslator = {
    _words: [],

    translate: function () {
        var $this = this;
        $('[data-sw-translate]').each(function () {
            $(this).html($this._tryTranslate($(this).html()));
            $(this).val($this._tryTranslate($(this).val()));
            $(this).attr('title', $this._tryTranslate($(this).attr('title')));
        });
    },

    setControllerSummary: function () {
        $.ajax({
            type: "get",
            async: true,
            url: $("#input_baseUrl").val(),
            dataType: "json",
            success: function (data) {
                var summaryDict = data.ControllerDesc;
                var id, controllerName, strSummary;
                $("#resources_container .resource").each(function (i, item) {
                    id = $(item).attr("id");
                    if (id) {
                        controllerName = id.substring(9);
                        strSummary = summaryDict[controllerName];
                        if (strSummary) {
                            $(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" style="color:#10a54a" title="' + strSummary + '">' + strSummary + '</li>');
                        }
                    }
                });
            }
        });
    },
    _tryTranslate: function (word) {
        return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
    },
    learn: function (wordsMap) {
        this._words = wordsMap;
    }
};

/* jshint quotmark: 漢化 */
window.SwaggerTranslator.learn({
    "Warning: Deprecated": "警告:已過期",
    "Implementation Notes": "實現備註",
    "Response Class": "響應類",
    "Status": "狀態",
    "Parameters": "參數",
    "Parameter": "參數",
    "Value": "",
    "Description": "描述",
    "Parameter Type": "參數類型",
    "Data Type": "數據類型",
    "Response Messages": "響應消息",
    "HTTP Status Code": "HTTP狀態碼",
    "Reason": "緣由",
    "Response Model": "響應模型",
    "Request URL": "請求URL",
    "Response Body": "響應體",
    "Response Code": "響應碼",
    "Response Headers": "響應頭",
    "Hide Response": "隱藏響應",
    "Headers": "",
    "Try it out!": "試一下!",
    "Show/Hide": "顯示/隱藏",
    "List Operations": "顯示操做",
    "Expand Operations": "展開操做",
    "Raw": "原始",
    "can't parse JSON.  Raw result": "沒法解析JSON. 原始結果",
    "Model Schema": "模型架構",
    "Model": "模型",
    "apply": "應用",
    "Username": "用戶名",
    "Password": "密碼",
    "Terms of service": "服務條款",
    "Created by": "建立者",
    "See more at": "查看更多:",
    "Contact the developer": "聯繫開發者",
    "api version": "api版本",
    "Response Content Type": "響應Content Type",
    "fetching resource": "正在獲取資源",
    "fetching resource list": "正在獲取資源列表",
    "Explore": "瀏覽",
    "Show Swagger Petstore Example Apis": "顯示 Swagger Petstore 示例 Apis",
    "Can't read from server.  It may not have the appropriate access-control-origin settings.": "沒法從服務器讀取。可能沒有正確設置access-control-origin。",
    "Please specify the protocol for": "請指定協議:",
    "Can't read swagger JSON from": "沒法讀取swagger JSON於",
    "Finished Loading Resource Information. Rendering Swagger UI": "已加載資源信息。正在渲染Swagger UI",
    "Unable to read api": "沒法讀取api",
    "from path": "從路徑",
    "server returned": "服務器返回"
});

$(function () {
    window.SwaggerTranslator.translate();
    window.SwaggerTranslator.setControllerSummary();
});

 

3. 修改App_Start中的SwaggerConfig.cs文件,主要代碼有下面兩處地方

 .EnableSwagger(c => {

        //設置控制器上的註釋顯示
        var xmlFile = string.Format("{0}/Doc/Project.Example.Web.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        c.CustomProvider((defaultProvider) => new SwaggerControllerDescProvider(defaultProvider, xmlFile));

})

.EnableSwaggerUi(c => {

       //注入自定義的js文件 

       c.InjectJavaScript(thisAssembly, "Project.Example.Web.Scripts.Swagger-Custom.js");

});

Project.Example.Web.Scripts.Swagger-Custom.js 這是咱們在第二步中定義的資源文件,資源文件名的命名規則以下:文件所在項目的命名空間.文件徑路.文件名

相關文章
相關標籤/搜索