1.创建asp.net core webApi项目
默认会引入swagger的Nuget包
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
2.配置基本信息和中文注释(默认是没有中文注释的)
2.1创建一个新的controller
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;namespace webapi.Controllers
{/// <summary>/// 学生接口/// </summary>[Route("api/[controller]")][ApiController]public class StudentController : ControllerBase{/// <summary>/// 获取学生列表/// </summary>/// <returns></returns>[HttpGet]public ActionResult GetList(){return Ok("学生列表");}/// <summary>///根据Id查询/// </summary>/// <param name="Id">学生Id</param>/// <returns></returns>[HttpGet("{Id}")]public ActionResult GetById(int Id){return Ok();}/// <summary>/// 获取token/// </summary>/// <param name="token"></param>/// <returns></returns>[HttpGet("{id}/{name}")]public string GetToken([FromHeader] string token){return "123";}/// <summary>/// 添加学生信息/// </summary>/// <param name="stu">学生信息</param>/// <returns></returns>[HttpPost]public ActionResult Add([FromBody] StudentInfo stu){return Ok();}/// <summary>/// 修改学生信息/// </summary>/// <param name="stu">学生信息</param>/// <param name="stu"></param>/// <returns></returns>[HttpPut]public ActionResult Update([FromBody] StudentInfo stu){return Ok();}/// <summary>///根据学生学号删除学生/// </summary>/// <param name="Id">学号</param>/// <returns></returns>[HttpDelete("{Id}")]public ActionResult DeletById(int Id){return Ok();}}
}
2.2创建学生类
namespace webapi
{/// <summary>///学生表/// </summary>public class StudentInfo{/// <summary>///学号/// </summary>public int Sno { get; set; }/// <summary>/// 姓名/// </summary>public string Name { get; set; }/// <summary>/// 年龄/// </summary>public int Age { get; set; }}
}
2.3 生成api中文注释xml(会把控制器上的方法和参数的中文注释生成xml文档)
选择项目-属性-生成-输出-勾选文档文件,xml文档文件路径可以默认
也可以直接双击项目,进入项目配置页面输入
<GenerateDocumentationFile>True</GenerateDocumentationFile>
builder.Services.AddSwaggerGen(p =>{p.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo(){Contact = new Microsoft.OpenApi.Models.OpenApiContact(){Email = "peng@g.com",Name = "pzx",Url = new Uri("http://www.baidu.com")},Description = "swagger设置基本信息",Title = "webapi练习"});//加载api中文注释,true是加载控制器上的注释p.IncludeXmlComments(AppContext.BaseDirectory + Assembly.GetExecutingAssembly().GetName().Name + ".xml", true);});
运行项目-中文注释就出来了
3.默认的swaggerUI不是太好看我们可以使用自定义的UI
Nuget下载:IGeekFan.AspNetCore.Knife4jUI
<ItemGroup><PackageReference Include="IGeekFan.AspNetCore.Knife4jUI" Version="0.0.13" /><PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" /></ItemGroup>
3.1配置使用Knife4jUI
// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()){app.UseSwagger();app.UseSwaggerUI(p =>{p.SwaggerEndpoint("/swagger/v1/swagger.json", "wepai");p.RoutePrefix = "swagger";//设置前缀,默认swagger});//使用自定义UIapp.UseKnife4UI(p =>{p.SwaggerEndpoint("/swagger/v1/swagger.json", "wepai");p.RoutePrefix = "";//设置前缀,默认swagger});}
swagger默认使用的swaggerUI,运行路径是
http://localhost:5160/swagger/index.html
要使用Knife4jUI可以把默认的swaggerUI的配置注释掉,把自己路由前缀设置为swagger
如果两个ui都想保留,就把前缀设置未不同,我这swaggerUI的前缀是swagger,Knife4jUI的前缀是空字符串
项目运行选择UI可以在launchSettings.json文件配置 lauchUrl和自己设置的RoutePrefix 值保持一直就可以了。
运行看效果,比默认的ui看起来更加的整洁
4.swaggerUI 配置 Bearer认证
builder.Services.AddSwaggerGen(p =>{p.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo(){Contact = new Microsoft.OpenApi.Models.OpenApiContact(){Email = "peng@g.com",Name = "pzx",Url = new Uri("http://www.baidu.com")},Description = "swagger设置基本信息",Title = "webapi练习"});//Bearer 的scheme定义var securityScheme = new OpenApiSecurityScheme(){Description = "JWT Authorization 头使用Bearer 体系方案. 例: \"Authorization: Bearer 你的token\"",Name = "Authorization",//参数添加在头部In = ParameterLocation.Header,//使用Authorize头部Type = SecuritySchemeType.Http,//内容为以 bearer开头Scheme = JwtBearerDefaults.AuthenticationScheme,//加了这个就不需要 输入Bearer 空格了,只要输入token就可以了BearerFormat = "JWT"};//把所有方法配置为增加bearer头部信息var securityRequirement = new OpenApiSecurityRequirement{{new OpenApiSecurityScheme{Reference = new OpenApiReference{Type = ReferenceType.SecurityScheme,Id = "JWT认证"}},new string[] {}}};//注册到swagger中p.AddSecurityDefinition("JWT认证", securityScheme);p.AddSecurityRequirement(securityRequirement);//加载api中文注释p.IncludeXmlComments(AppContext.BaseDirectory + Assembly.GetExecutingAssembly().GetName().Name + ".xml", true);});
效果如下
Knife4jUI加请求头就比较方便(直接添加就行了,不需要配置)
配置和生成jwt可以看我下面的文章
https://blog.csdn.net/qq_41942413/article/details/134680803?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22134680803%22%2C%22source%22%3A%22qq_41942413%22%7D