Swagger
是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful
风格的 Web 服务。是一款RESTFUL
接口的文档在线自动生成+功能测试软件。主要目的是构建标准的、稳定的、可重用的、交互式的API以及简单方便的功能测试。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger
让部署管理和使用功能强大的API从未如此简单。
作用:
asp.net core
项目nuget
上安装Swashbuckle.AspNetCore
Swashbuckle
有三个主要组件:Swashbuckle.AspNetCore.Swagger
:一个Swagger
对象模型和中间件,用于将SwaggerDocument
对象公开为JSON
端点。Swashbuckle.AspNetCore.SwaggerGen
:一个Swagger
生成器,可SwaggerDocument
直接从路由,控制器和模型构建对象。它通常与Swagger
端点中间件结合使用,以自动显示Swagger JSON
。Swashbuckle.AspNetCore.SwaggerUI
:Swagger UI
工具的嵌入式版本。它解释了Swagger JSON
,以便为描述Web API
功能构建丰富,可定制的体验。它包括用于公共方法的内置测试工具。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" });
});
}
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");
});
}
在 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);
});
}
在查看/swagger/v1/swagger.json
文件后发现是没有配置parh
打开后内容是:
{"swagger":"2.0","info":{"version":"v1","title":"My API"},"paths":{},"definitions":{}}
解决:该项目中未添加API控制器,注意必须是API控制器,并且需要在处理方法上添加HTTP标记
///
/// Delete
///
/// 删除id列表
/// 被成功删除id列表
[HttpDelete]
public ActionResult<IEnumerable<string>> Delete(params string[] ids)
{
if (ids == null)
return NoContent();
return ids;
}
///
/// Update
///
/// Update id
///
[HttpPut]
public IActionResult Update(string id)
{
return Content("Update id:" + id);
}
///
/// Add
///
/// Add ids
///
[HttpPost]
public IActionResult Add(params string[] param)
{
return Content(string.Join(",", param));
}
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
{
///
/// Delete
///
/// 删除id列表
/// 被成功删除id列表
//[HttpDelete]
public ActionResult<IEnumerable<string>> Delete(params string[] ids)
{
if (ids == null)
return NoContent();
return ids;
}
///
/// Update
///
/// Update id
///
[HttpPut]
public IActionResult Update(string id)
{
return Content("Update id:" + id);
}
///
/// Add
///
/// Add ids
///
[HttpPost]
public IActionResult Add(params string[] param)
{
return Content(string.Join(",", param));
}
}
}
原因:控制器中出现未被HTTP标记的方法
解决方案:删除该方法或者添加相应的HTTP标记
官网文档:https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=netcore-cli#add-and-configure-swagger-middleware
更多请参考swagger官网:https://swagger.io/