記錄一下,方便自己和朋友查找。。Swagger對於接口項目確實有很大的幫助。
效果:
一.WebApi中配置Swagger
1.運行Nuget:添加Swashbuckle 和Swagger.Net.UI 第一個包就是啦
2.修改一下API項目屬性
3.在App_Start文件夾下,修改SwaggerNet.cs:
修改SwaggerConfig.cs:
public class SwaggerConfig { public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "BnWebApi"); //添加XML解析 c.IncludeXmlComments(GetXmlCommentsPath()); c.BasicAuth("basic").Description("Basic HTTP Authentication"); //取消注釋是為了請求驗證 }) .EnableSwaggerUi(c => { c.InjectJavaScript(thisAssembly, "BnWebApi.CustomContent.api-key-header-auth.js");//取消注釋是為了請求驗證 }); } //添加XML解析 private static string GetXmlCommentsPath() { return string.Format("{0}/bin/WebApiSwagger.xml", System.AppDomain.CurrentDomain.BaseDirectory); } }
不需要請求驗證的,把兩行請求驗證代碼注釋掉。
完成了,運行項目后,查看
二:帶有請求驗證的Swagger配置。
有驗證的話,上述的Swagger配置調用接口,調用不了的。會提示驗證不通過。
1.在項目添加CustomContent文件夾,再添加api-key-header-auth.js
JS代碼如下:
(function () { $(function () { $('#input_apiKey').show(); $('#input_apiKey').on('change', function () { var key = this.value; if (key && key.trim() !== '') { swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header")); } }); }); })();
修改JS文件的屬性:
2.修改SwaggerConfig.cs代碼如下:
3.運行項目,在Api_Key中輸入需要驗證的Token
再去測試發現Swagger接口已經通了。
放一下對比圖: