1.打開NuGet程序包api
2.安裝下面兩個程序包瀏覽器
3.安裝完後會出現SwaggerConfig.cs類,並修改裏面的內容框架
代碼:post
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace WebApplication1 { public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "WebApp");
c.IncludeXmlComments(GetXmlCommentsPath());this
}) } private static string GetXmlCommentsPath() { return $@"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\WebApi.XML"; } }
4.添加WebApi.cs類spa
代碼:3d
namespace WebApi { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi1", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi2", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { action="get",id = RouteParameter.Optional } ); } } }
5.修改Global.asax類調試
代碼:code
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); GlobalConfiguration.Configure(WebApiConfig.Register); //這是要加的 } }
6.設置須要調試的類blog
7.設置生成的XML文檔
8.運行項目,打開瀏覽器輸入http://localhost:23092/swagger/
結果展現:
注意:
在使用Swagger WebApi文檔框架時,一個Controll中寫多個Post接口時,在MVC4中會提示沒法識別的多個post請求,緣由是WebApiConfig中默認路由配置中是沒有配置{action}引發的。
【在MVC5中沒有此問題,緣由是MVC5有Route[" "]特性,MVC4中不支持】
解決方案:
方法1:修改WebApiConfig文件
//默認配置 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //修改後配置 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
方法2:MVC5中能夠不修改默認配置文件,而使用Route特性來指定
/// <summary> /// POST請求1 /// ///api/Member /// </summary> /// <param name="value"></param> public void Post([FromBody]string value) { } /// <summary> /// POST請求2 /// api/Member/Login /// </summary> /// <param name="loginId"></param> /// <param name="password"></param> /// <returns></returns> [HttpPost, Route("api/Member/Login")] public string Login([FromBody]string loginId, [FromBody]string password) { return ""; }
附帶:隱藏接口
在使用Swagger須要隱藏不開放的API
能夠在SwaggerConfig.cs中加入
/// <summary> /// 隱藏接口,不生成到swagger文檔展現 /// </summary> [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Class)] public partial class HiddenApiAttribute : System.Attribute { } public class HiddenApiFilter : IDocumentFilter { /// <summary> /// 重寫Apply方法,移除隱藏接口的生成 /// </summary> /// <param name="swaggerDoc">swagger文檔文件</param> /// <param name="schemaRegistry"></param> /// <param name="apiExplorer">api接口集合</param> public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions) { if (Enumerable.OfType<HiddenApiAttribute>(apiDescription.GetControllerAndActionAttributes<HiddenApiAttribute>()).Any()) { string key = "/" + apiDescription.RelativePath; if (key.Contains("?")) { int idx = key.IndexOf("?", System.StringComparison.Ordinal); key = key.Substring(0, idx); } swaggerDoc.paths.Remove(key); } } } }
而且在SwaggerConfig.cs 中加入
c.DocumentFilter<HiddenApiFilter>();
搞定