【转】ASP.NET Web API 使用Swagger生成在线帮助测试文档,支持多个GET
以下為教程:
?
在現(xiàn)有webapi項(xiàng)目中,nuget安裝以下兩個插件
swagger.net.ui
swashbuckle
?安裝完畢后可以卸載Swagger.NET,此處不需要!
安裝完畢后屏蔽以下代碼
直接運(yùn)行調(diào)試
在瀏覽器的目錄后面加上/swagger即可跳轉(zhuǎn)到swagger調(diào)試頁
此時(shí)如果沒有注釋.
項(xiàng)目屬性里添加xml注釋的生成
修改App_Start下的SwaggerConfig.cs文件
?添加如下代碼
GlobalConfiguration.Configuration.EnableSwagger(c =>{c.IncludeXmlComments(GetXmlCommentsPath()); ...... }?
protected static string GetXmlCommentsPath(){return System.String.Format(@"{0}\bin\你的xml文件名.XML", System.AppDomain.CurrentDomain.BaseDirectory);}此時(shí)重新生成瀏覽可以獲取正確的注釋并調(diào)試了.
?異常解決
報(bào)錯
webapi 配置swagger出現(xiàn)問題:
Swagger Not supported by Swagger 2.0: Multiple operations with path 解決方法
一個controller中只能有一個HttpGet請求,多了就會報(bào)錯。建議減少重載方法,將其他Get方法分開
如果在swagger.config中加上c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());則會只顯示第一個get方法
加了上面的方法后,get可能會只顯示一條記錄
WebAPI 默認(rèn)只支持一個get方法,支持多個Get需要修改
RouteConfig文件
routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });?
因此,需要對swagger.net也添加相應(yīng)的支持.(無效)
?
public static void RegisterRoutes(RouteCollection routes){routes.IgnoreRoute("{resource}.axd/{*pathInfo}");RouteTable.Routes.MapHttpRoute(name: "SwaggerApi",routeTemplate: "api/docs/{controller}/{action}",defaults: new { swagger = true });routes.MapRoute(name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });}?
以上,均非有效解決辦法,正確的辦法入戲:
?
config.Routes.MapHttpRoute(name: "DefaultApi",// routeTemplate: "api/{controller}/{id}",routeTemplate: "api/{controller}/{action}/{id}",//defaults: new { id = RouteParameter.Optional }defaults: new { controller = "Home", action = "Index", id = RouteParameter.Optional });?
?
?
完成
?
異常3
fetching resource list: http://localhost:8011/swagger/docs/v1; Please wait.
一直顯示這個界面
?
只返回Json?Result的content?negotiation代替Web?Api中默認(rèn)的content?negotiation造成的.
WebApiConfig中,行:
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
臨時(shí)屏蔽即可
總結(jié)
以上是生活随笔為你收集整理的【转】ASP.NET Web API 使用Swagger生成在线帮助测试文档,支持多个GET的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】C#Socket编程详解(一)TC
- 下一篇: 【转】MFC与.NET的区别