- A+
所属分类:.NET技术
使用特性来描述接口而不是xml文件,使用特性可自定义接口在swaggerUI上的描述
安装nuget包:Swashbuckle.AspNetCore.SwaggerUI
和Swashbuckle.AspNetCore.Annotations
,配置swagger:
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.Configure<IConfiguration>(Configuration); 4 5 6 #region 添加Swagger 7 services.AddSwaggerGen(opt=> { 8 opt.SwaggerDoc(swaggerDocName, new OpenApiInfo() { Version="v1",Title="watch api",Description="watch"}); 9 //使用annotation来描述接口 不依赖xml文件 10 opt.EnableAnnotations(); 11 12 // 下面两句,将swagger文档中controller名使用GroupName替换 13 // 在Swagger中,一个Tag可以看作是一个API分组 14 opt.DocInclusionPredicate((_, apiDescription) => string.IsNullOrWhiteSpace(apiDescription.GroupName) == false); 15 opt.SwaggerGeneratorOptions.TagsSelector = (apiDescription) => new[] { apiDescription.GroupName }; 16 17 }); 18 19 #endregion 20 21 services.AddControllers(); 22 23 24 25 26 27 }
使用上面注入好的swagger
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } #region Swagger app.UseSwagger(opt => { // 相对路径加载swagger文档 //opt.RouteTemplate = "swagger/{documentName}"; }) .UseSwaggerUI(opt => { opt.SwaggerEndpoint($"{swaggerDocName}/swagger.json", "watch API文档"); }); #endregion app.UseHttpsRedirection(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
Controller和Action上使用特性:ApiExplorerSettings
和SwaggerOperation
:
namespace WatchApi.Controllers { [ApiExplorerSettings(GroupName = "品牌")] [Route("[controller]/[action]")] [ApiController] public class pinpaiController : ControllerBase { private readonly IMapper _mapper; private readonly IpinpaiService _pinpaiserver; public pinpaiController(IpinpaiService pinpaiserver, IMapper mapper) { _pinpaiserver = pinpaiserver; _mapper = mapper; } [SwaggerOperation(Summary = "获取列表")] [HttpGet] public ResponseModel<IEnumerable<pinpai>> Get() { var resModel = _pinpaiserver.GetListpinpai(); return ResponseModel.Succeed<IEnumerable<pinpai>>(resModel); } [SwaggerOperation(Summary = "添加商品")] [HttpPost,Authorize] public ResponseModel Add(pinpai pinpaiobj) { //pinpaiRequest obj //var pinpaiobj1 = _mapper.Map<pinpai>(pinpaiobj); var result = _pinpaiserver.Addpinpai(pinpaiobj); if (result) { return ResponseModel.Succeed(); } else { return ResponseModel.Failed(); } } [HttpPost] public ResponseModel<string> Add1([FromForm] string name) { return ResponseModel.Succeed(name); } } }
访问https://localhost:5001/swagger/index.html 换成自己的调试链接
效果图如下