小言_互联网的博客

.Net Core3.1 swagger 文档添加 不用xml配置

344人阅读  评论(0)

  之前学习的框架中 swagger 中的 API 列表使用 xml 文档 去手动添加的,不能随着项目的进度自动更新API列表内容,每新增一个接口就要去xml文档里手动添加,个人觉得很麻瓜,于是便寻得,使用特性的方式自动生成 swagger 中API列表的方式,觉得很好用,便记录下来

.Net core3.1 swagger 文档添加 不用xml配置

  • 使用特性来描述接口而不是xml文件,使用特性可自定义接口swagger UI上的描述
  • 安装NuGet包:Swashbuckle.AspNetCore.SwaggerUISwashbuckle.AspNetCore.Annotations

配置 swagger :

public void ConfigureServices(IServiceCollection services)
{
   
	services.Configure(Configuration);
  	// 注入 Swagger
	services.AddSwaggerGen(opt =>
	{
   
		opt.SwaggerDoc(swaggerDocName, new OpenApiInfo()
		{
   
			Version = "v1", Title = "watch api", Description = "watch"
		});
		//使用annotation来描述接口  不依赖xml文件
		opt.EnableAnnotations();
		// 下面两句,将swagger文档中controller名使用GroupName替换
		// 在Swagger中,一个Tag可以看作是一个API分组
		opt.DocInclusionPredicate((_, apiDescription) => string.IsNullOrWhiteSpace(apiDescription.GroupName) == false);
		opt.SwaggerGeneratorOptions.TagsSelector = (apiDescription) => new []
		{
   
			apiDescription.GroupName
		};
	});
	services.AddControllers();
}
 // 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();
     }
     // Swagger
     app.UseSwagger(opt =>
     {
   
         // 相对路径加载swagger文档
         //opt.RouteTemplate = "swagger/{documentName}";
     }).UseSwaggerUI(opt =>
     {
   
         opt.SwaggerEndpoint($ "{swaggerDocName}/swagger.json", "watch API文档");
     });
     
     app.UseHttpsRedirection();
     app.UseRouting();
     app.UseEndpoints(endpoints =>
     {
   
         endpoints.MapControllers();
     });
 }

Controller 和 Action 上使用特性:ApiExplorerSettingsSwaggerOperation

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://blog.csdn.net/qq_43562262/article/details/115764407
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场