c# webapi 配置swagger的方法
如何配置swagger?
在使用項目中,我們希望去查看我們的webapi的測試,那么我們是需要去有一個集成的測試的。
步驟
1.在nutget管理包中下載swagger包。
2.這樣會在App_start 文件夾中出現(xiàn)swaggerconfig.cs 和swaggerNet.cs,
這個時候就需要配置的時候了。
3.取消下面的注釋(swaggerconfig.cs)
c.IncludeXmlComments(string.Format("{0}/bin/ThinkingSpace.XML", System.AppDomain.CurrentDomain.BaseDirectory));
當(dāng)然我們?yōu)榱舜a的模塊化,可以封裝到一個方法中:
private static string GetXmlCommentsPath() { return $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\GetDocumentation.XML"; }
好吧,ok,我們知道了這個配置了。
那么我們需要再bin目錄下創(chuàng)建一個xml,推薦是項目名.xml.
4.那么接下來就是swaggerNet.cs配置.
using System; using System.IO; using System.Web; using System.Web.Http; using System.Web.Http.Description; using System.Web.Http.Dispatcher; using System.Web.Routing; using Swagger.Net; [assembly: WebActivator.PreApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet), "PreStart")] [assembly: WebActivator.PostApplicationStartMethod(typeof(ThinkingSpace.App_Start.SwaggerNet), "PostStart")] namespace ThinkingSpace.App_Start { public static class SwaggerNet { public static void PreStart() { RouteTable.Routes.MapHttpRoute( name: "SwaggerApi", routeTemplate: "api/docs/{controller}", defaults: new { swagger = true } ); } public static void PostStart() { var config = GlobalConfiguration.Configuration; config.Filters.Add(new SwaggerActionFilter()); try { config.Services.Replace(typeof(IDocumentationProvider), new XmlCommentDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/ThinkingSpace.XML"))); } catch (FileNotFoundException) { throw new Exception("Please enable \"XML documentation file\" in project properties with default (bin\\ThinkingSpace.XML) value or edit value in App_Start\\SwaggerNet.cs"); } } } }
統(tǒng)一我們需要修改xml的位置即可。
注意
我們需要在webapi中只能存在一個get,否則會報錯,因為需要符合restful 標(biāo)準(zhǔn)。
一個controller中只能有一個HttpGet請求,多了就會報錯。建議減少重載方法,將其他Get方法分開
如果在swagger.config中加上c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());則會只顯示第一個get方法
另:可以不安裝swagger ui for .net,安了有可能會報錯
以上就是c# webapi 配置swagger的方法的詳細內(nèi)容,更多關(guān)于c# 配置swagger的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C# 中的動態(tài)創(chuàng)建組件(屬性及事件)的實現(xiàn)思路及方法
這篇文章主要介紹了C# 中的動態(tài)創(chuàng)建組件,有需要的朋友可以參考一下2013-12-12Silverlight文件上傳下載實現(xiàn)方法(下載保存)
這篇文章主要介紹了Silverlight文件上傳下載實現(xiàn)方法(下載保存) ,需要的朋友可以參考下2015-11-11c#linq里的Skip和Take實現(xiàn)分頁或遍歷
LINQ的優(yōu)勢在于它提供了一種直觀、類型安全的方式來操作各種類型的數(shù)據(jù),查詢常需要獲取一部分數(shù)據(jù),為了實現(xiàn)這一功能,LINQ提供了Take?和Skip運算符,Take運算符用于從一個序列中返回指定個數(shù)的元素,Skip運算符用于從一個序列中跳過指定個數(shù)的元素2024-01-01C# 實現(xiàn)PPT 每一頁轉(zhuǎn)成圖片過程解析
這篇文章主要介紹了C# 實現(xiàn)PPT 每一頁轉(zhuǎn)成圖片過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09