Asp.net WebApi Swagger Tag 标记分组归纳显示Api接口路由

发布时间 2023-12-29 11:20:14作者: o天风o
官方文档说明地址   https://swagger.io/docs/specification/2-0/grouping-operations-with-tags/
创建一个自定义的特性类

 public class ControllerGroupAttribute : Attribute
    {
        public ControllerGroupAttribute(string groupName)
        {
            if (string.IsNullOrWhiteSpace(groupName))
            {
                throw new ArgumentNullException("分组信息不能为空");
            }
            GroupName = groupName;
        }

        /// <summary>
        /// 
        /// </summary>
        public string GroupName { get; set; }
    }
配置Swagger的分组规则

GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {

                        c.SingleApiVersion("v1", "SwaggerGroupTest");
                        c.IncludeXmlComments(GetXmlCommentsPath());
                        c.GroupActionsBy(apiDesc => apiDesc.GetControllerAndActionAttributes<ControllerGroupAttribute>().Any()
                        ? apiDesc.GetControllerAndActionAttributes<ControllerGroupAttribute>().First().GroupName : apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName
                        );                    
                    })
                .EnableSwaggerUi(c =>
                    {
                        
                    });

下图为Swagger.Config的代码图

接下来就是使用特性 标注在Controller 上或者Action上 去进行分组
[ControllerGroupAttribute("jazgh")]
namespace SwaggerGroupTest.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/User/{action}")]
    
    public class UserController : ApiController
    {
        [ControllerGroup("nczgk")]
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult PeopleList()
        {
            return Ok(new string[] { "张三", "李四", "王五" });
        }
        /// <summary>
        /// 打招呼
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult SayHello()
        {
            return Ok("Hello");
        }
    }
}

效果图如下

 

标注在Action上的会归类到单独的tag 标记中  没有就按照原有的Controller 名称分类  

实际得到的json 描述如上图所示 和官网文档说的使用tag标记符合  官网文档地址在文章最开头