本文主要是介绍创建Net8WebApi自动创建OpenApi集成swagger,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题:用Net8创建WebAPI时勾选启动OpenAPI,项目自动集成了Swagger,但是接口注释没有展示?
解决:
1.需要生成Api项目的XML文件。操作如下:
2.生成XML文件后,还需要在启动类Program.cs里面配置SwaggerUI的文件映射配置;代码如下:
// 配置swagger的注释xml
builder.Services.AddSwaggerGen(c =>
{var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);c.IncludeXmlComments(xmlPath);});
整体的Program.cs代码如下:
using AnNeng.Service.Application.Test;
using System.Reflection;var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ITestService, TestService>(); // 依赖注入配置// 配置swagger的注释xml
builder.Services.AddSwaggerGen(c =>
{var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);c.IncludeXmlComments(xmlPath);});var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI();
}app.UseAuthorization();app.MapControllers();app.Run();
3.问题解决,效果如下
这篇关于创建Net8WebApi自动创建OpenApi集成swagger的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!