net core 3.1 swagger文档添加 不用xml配置
DotNetCore实战
共 3750字,需浏览 8分钟
·
2020-11-02 11:13
使用特性来描述接口而不是xml文件,使用特性可自定义接口在swaggerUI上的描述
安装nuget包:Swashbuckle.AspNetCore.SwaggerUI
和Swashbuckle.AspNetCore.Annotations
,配置swagger:
1 public void ConfigureServices(IServiceCollection services)
2 {
3 services.Configure(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> Get()
{
var resModel = _pinpaiserver.GetListpinpai();
return ResponseModel.Succeed>(resModel);
}
[SwaggerOperation(Summary = "添加商品")]
[HttpPost,Authorize]
public ResponseModel Add(pinpai pinpaiobj)
{
//pinpaiRequest obj
//var pinpaiobj1 = _mapper.Map(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 换成自己的调试链接
效果图如下
.NET Core实战项目之CMS 第一章 入门篇-开篇及总体规划
【.NET Core微服务实战-统一身份认证】开篇及目录索引
Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南)
.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了
用abp vNext快速开发Quartz.NET定时任务管理界面
评论