.net core WebApi 使用Swagger生成API文档
生活随笔
收集整理的這篇文章主要介紹了
.net core WebApi 使用Swagger生成API文档
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
關(guān)于 Swagger
Swagger能成為最受歡迎的REST APIs文檔生成工具之一,有以下幾個(gè)原因:
- Swagger 可以生成一個(gè)具有互動(dòng)性的API控制臺(tái),開發(fā)者可以用來快速學(xué)習(xí)和嘗試API。
- Swagger 可以生成客戶端SDK代碼用于各種不同的平臺(tái)上的實(shí)現(xiàn)。
- Swagger 文件可以在許多不同的平臺(tái)上從代碼注釋中自動(dòng)生成。
- Swagger 有一個(gè)強(qiáng)大的社區(qū),里面有許多強(qiáng)悍的貢獻(xiàn)者。
Swagger 文檔提供了一個(gè)方法,使我們可以用指定的 JSON摘要來描述你的 API,包括了比如 names、order 等 API 信息。
1、安裝Swashbuckle.AspNetCore
using Swashbuckle.AspNetCore.Swagger;
public void ConfigureServices(IServiceCollection services){//注冊(cè)Swagger生成器,定義一個(gè)和多個(gè)Swagger 文檔services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });//設(shè)置版本號(hào),標(biāo)題var xmlPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "SwaggerApi.xml");//為Swagger設(shè)置xml文檔注釋路徑c.IncludeXmlComments(xmlPath);//只有設(shè)置了xmlm文檔的路徑生成的文檔才會(huì)有注釋c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader參數(shù) });services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}2、啟用中間件服務(wù)
public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseHsts();}//啟用中間件服務(wù)生成Swagger作為JSON終結(jié)點(diǎn) app.UseSwagger();//啟用中間件服務(wù)對(duì)swagger-ui,指定Swagger JSON終結(jié)點(diǎn)app.UseSwaggerUI(c =>{c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");c.RoutePrefix = string.Empty;});app.UseHttpsRedirection();app.UseMvc();}?
3、新建HttpHeaderOperation
public void Apply(Operation operation, OperationFilterContext context){if (operation.Parameters == null){operation.Parameters = new List<IParameter>();}var actionAttrs = context.ApiDescription.ActionAttributes();var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));if (isAuthorized == false) //提供action都沒有權(quán)限特性標(biāo)記,檢查控制器有沒有 {var controllerAttrs = context.ApiDescription.ControllerAttributes();isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));}var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));if (isAuthorized && isAllowAnonymous == false){operation.Parameters.Add(new NonBodyParameter(){Name = "Authorization", //添加Authorization頭部參數(shù)In = "header",Type = "string",Required = false,Description = "access token"});}}public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context){throw new NotImplementedException();}4、配置XML文檔路徑
?5、地址欄輸入http://localhost:{port}/swagger/index.html
?
轉(zhuǎn)載于:https://www.cnblogs.com/qzxj/p/10783600.html
總結(jié)
以上是生活随笔為你收集整理的.net core WebApi 使用Swagger生成API文档的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小游戏《羊了个羊》开发商被指抄袭“惯犯”
- 下一篇: OpenCV自带dnn的Example研