在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。是一款RESTFUL接口的文档在线自动生成+功能测试软件。主要目的是构建标准的、稳定的、可重用的、交互式的API以及简单方便的功能测试。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。 作用: 1. 根据基于规范的标准设计和建模API 2. 几乎可以用任何语言为您的API构建稳定,可重用的代码 3. 使用交互式API文档改善开发人员体验 4. 对您的API执行简单的功能测试,而无需开销 5. 在您的API架构中设置和实施API样式指南 1.新建asp.net core项目 2.nuget上安装Swashbuckle.AspNetCore Swashbuckle有三个主要组件:
3.在Startup的 ConfigureServices配置服务中添加中间件 public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); } 4.在Startup的 Configure配置服务中启用中间件 public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.InjectJavascript(""); c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); } 5.启动程序,然后键入url swagger/index.html或者swagger
6.修改Web API项目首页重定向 在 Properties >> launchSettings.json文件中更改默认配置 >> 启用 "launchUrl": "swagger"配置 { "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:49833", "sslPort": 44387 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "SwaggerTest": { "commandName": "Project", "launchBrowser": true, "launchUrl": "http://localhost:49833/swagger", "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
7.为控制器中每个方法添加注释,启用XML注释为未记录的公共类型和成员提供调试信息 项目 >> 属性 >> 生成
修改Startup的 ConfigureServices配置服务 public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); //添加xml文件 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
8.添加控制器,启动 创建成功
二 、注意事项1.启动后出现 No operations defined in spec! 问题在查看/swagger/v1/swagger.json文件后发现是没有配置parh 打开后内容是: {"swagger":"2.0","info":{"version":"v1","title":"My API"},"paths":{},"definitions":{}}
解决:该项目中未添加API控制器,注意必须是API控制器,并且需要在处理方法上添加HTTP标记 /// <summary> /// Delete /// </summary> /// <param name="ids">删除id列表</param> /// <returns>被成功删除id列表</returns> [HttpDelete] public ActionResult<IEnumerable<string>> Delete(params string[] ids) { if (ids == null) return NoContent(); return ids; } /// <summary> /// Update /// </summary> /// <param name="id">Update id</param> /// <returns></returns> [HttpPut] public IActionResult Update(string id) { return Content("Update id:" + id); } /// <summary> /// Add /// </summary> /// <param name="param">Add ids</param> /// <returns></returns> [HttpPost] public IActionResult Add(params string[] param) { return Content(string.Join(",", param)); } 2.启动后出现 Failed to load API definition. 错误 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace SwaggerTest.Controllers { [Route("api/[controller]")] [ApiController] public class DefaultController : ControllerBase { /// <summary> /// Delete /// </summary> /// <param name="ids">删除id列表</param> /// <returns>被成功删除id列表</returns> //[HttpDelete] public ActionResult<IEnumerable<string>> Delete(params string[] ids) { if (ids == null) return NoContent(); return ids; } /// <summary> /// Update /// </summary> /// <param name="id">Update id</param> /// <returns></returns> [HttpPut] public IActionResult Update(string id) { return Content("Update id:" + id); } /// <summary> /// Add /// </summary> /// <param name="param">Add ids</param> /// <returns></returns> [HttpPost] public IActionResult Add(params string[] param) { return Content(string.Join(",", param)); } } }
原因:控制器中出现未被HTTP标记的方法 解决方案:删除该方法或者添加相应的HTTP标记
更多请参考swagger官网:https://swagger.io/
|
请发表评论