1、添加引用
nugget中搜索添加引用:Swashbuckle.AspNetCore
2、添加服务
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //使用swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo() { Title = "CoreWebApi", Version = "v1", Description = "CoreWebApi_Description" }); var basePath = AppDomain.CurrentDomain.BaseDirectory; foreach (var name in Directory.GetFiles(basePath, "*.xml", SearchOption.AllDirectories)) { c.IncludeXmlComments(name); } }); }
3、添加中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(p => { p.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreWebApi V1"); });
app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
4、添加controller
[Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { SQLDbContext _dbContext; public UsersController(SQLDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// 新增用户 /// </summary> /// <param name="userDTO"></param> /// <returns></returns> [Route("Add")]
[HttpPost] public bool Add(UserDTO userDTO) { } /// <summary> /// 获取用户列表 /// </summary> /// <param name="userQueryPatameters"></param> /// <returns></returns> [Route("List")]
[HttpPost] public ReturnViewModel<UserViewModel> List(UserQueryPatameters userQueryPatameters) { } }
5、项目设置
项目右键,选择属性,勾选“XML文档文件”,如下图所示:
注意增加“取消显示警告”。
启动程序访问:https://localhost:5001/swagger/index.html