开发环境 Win10 VS2022 .NET8.0
1.从NuGet添加Swagger
在解决方案资源管理器中右键单击项目>管理 NuGet 包
将包源设置为“nuget.org”
确保启用“包括预发行”选项
在搜索框中输入“Swashbuckle.AspNetCore”
从“浏览”选项卡中选择最新的“Swashbuckle.AspNetCore”包,然后单击“安装”
2.将 Swagger 生成器添加到以下位置的服务集合中Program.cs:
builder.Services.AddControllers();builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
启用中间件 生成
app.UseSwagger();
app.UseSwaggerUI();app.UseSwaggerUI(options =>
{options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");options.RoutePrefix = string.Empty;
});
3.添加API控制器
创建api
// GET api/<myapi>/5/// <summary>/// getid/// </summary>/// <param name="id">id参数</param>/// <returns>valuestr</returns>[HttpGet("{id}")]public string Get(int id){return "value" + id;}// POST api/<myapi>[HttpPost]public string Post([FromBody] string value){//post逻辑代码return "myPost";}// PUT api/<myapi>/5[HttpPut("{id}")]public string Put(int id, [FromBody] string value){//put逻辑代码return "myPut";}// DELETE api/<myapi>/5[HttpDelete("{id}")]public string Delete(int id){//delete逻辑代码return "myDelete";}
4.F5运行 访问/swagger/index.html
5.try it out测试API
看到返回了 value111 即接口没问题
参考资料:
asp.net core - Swagger UI Authorization using IdentityServer4 returns Invalid redirect_uri - Stack Overflow
c# - What is AddEndpointsApiExplorer in ASP.NET Core 6 - Stack Overflow
Get started with Swashbuckle and ASP.NET Core | Microsoft Learn
Swagger 基础