日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

使用Swagger创建Api

發布時間:2025/5/22 编程问答 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用Swagger创建Api 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.首先創建一個web項目,選擇Mvc模板

?

2.右鍵點擊引用.管理Nuget程序包,瀏覽 搜索Swagger,下載安裝下面的包

?

3.安裝完后在App_Start里面會出現SwaggerConfig.cs類,并將SwaggerConfig類中的內容替換成下內容

using System.Web.Http; using WebActivatorEx; using UseSwagger; using Swashbuckle.Application; using System;[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]namespace UseSwagger {public class SwaggerConfig{public static void Register(){var thisAssembly = typeof(SwaggerConfig).Assembly;GlobalConfiguration.Configuration.EnableSwagger(c =>{c.SingleApiVersion("v1", "WebApp");}).EnableSwaggerUi(c =>{GetXmlCommentsPath();});}private static string GetXmlCommentsPath(){return string.Format(@"{0}\bin\UseSwagger.XML", AppDomain.CurrentDomain.BaseDirectory);}} }

?

4.在App_Start文件夾中創建一個WebApiConfig.cs內容為

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http;namespace UseSwagger.App_Start {public class WebApiConfig{public static void Register(HttpConfiguration config){// Web API 配置和服務// Web API 路由 config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new{id = RouteParameter.Optional});}} }

此時會發現?config.MapHttpAttributeRoutes();飄紅報錯.此時需在引用? Microsoft.AspNet.WebApi.WebHost? 包.然后就不報錯了.

?

5.在Global.asax調用剛才添加的類的Register方法.

6.右鍵項目->屬性->生成->勾上XML文檔文件

然后繼續點擊Web,設置默認打開頁面(此處若不設置默認打開頁面.運行項目將會報錯404,因為項目運行之后的地址不對.正確的地址是 項目地址/swagger/ui/index)

?

7.創建一個Controller,然后繼承ApiController,記得添加引用?using System.Web.Http;(若不繼承自ApiController則不會再Swagger頁面中顯示)

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc;namespace UseSwagger.Controllers {public class TestController : ApiController{// GET: Testpublic int Index(int a){return 0;}} }

至此Swagger已經可以使用了

?

轉載于:https://www.cnblogs.com/yan0720/p/11049915.html

總結

以上是生活随笔為你收集整理的使用Swagger创建Api的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。