.Net WebApi 添加Swagger

來源:互聯網
上載者:User

標籤:name   space   alc   script   屬性   main   oid   類型   lte   

前言

隨著互連網技術的發展,現在的網站架構基本都由原來的後端渲染,變成了:前端渲染、先後端分離的形態,而且前端技術和後端技術在各自的道路上越走越遠。
前端和後端的唯一聯絡,變成了API介面;API文檔變成了前後端開發人員聯絡的紐帶,變得越來越重要,swagger就是一款讓你更好的書寫API文檔的架構。

安裝
  1. 首先,建立WebApi類型的項目 TestSwagger

        

        2. 安裝Swashbuckle 包和swagger.Net.UI包

      

  3. 安裝完成之後,可以看到這些類與檔案都是安裝完成時swagger添加的

      

 

 

設定
  1. 設定輸出xml文檔檔案
    右鍵項目屬性—>產生—>勾選XML文檔檔案

       

運行

發生上述錯誤,請在,SwaggerNet.cs中,注釋類上面的兩行

 

 結果又報以下錯誤:

    

這時需要在SwaggerConfig.cs 檔案中 GlobalConfiguration.Configuration.EnableSwagger  添加c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

需要添加註釋則加:   c.IncludeXmlComments(string.Format("{0}/bin/TestService.XML", System.AppDomain.CurrentDomain.BaseDirectory));

需要在Swagger頁面添加自訂header:

需要在SwaggerConfig.cs 檔案中 c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();

增加新類:

namespace TestService.App_Start{    public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter    {        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)        {            if (operation.parameters == null)            {                operation.parameters = new List<Parameter>();            }            operation.parameters.Add(new Parameter                {                    name = "UserId",                    @in = "header",                    description = "User short name",                    required = true,                    type = "string"                });            operation.parameters.Add(new Parameter            {                name = "ClientId",                @in = "header",                description = "Client generated unique number",                required = true,                type = "string"            });        }    }}

  顯示效果

 

.Net WebApi 添加Swagger

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.