使用Swagger创建Api
生活随笔
收集整理的這篇文章主要介紹了
使用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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pandas 常用操作
- 下一篇: 爬虫基本库的使用---urllib库