在文档中对API方法进行分组 - 是否存在一些自定义属性

问题描述 投票:12回答:2

我有控制器喜欢

public class UserController : ApiController
{
  [Route("api/user")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  IHttpActionResult GetResumes() { ... }
}

哪个在swagger上产生像enter image description here这样的输出

有没有办法(除了通过推出自己的ISwaggerProvider或将两个控制器合并为一个来覆盖默认实现)来强制执行组名?就像是

public class UserController : ApiController
{
  [Route("api/user")]
  [MagicalAttributeName(Group="User")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  [MagicalAttributeName(Group="User")]
  IHttpActionResult GetResumes() { ... }
}
c# asp.net-web-api swagger-ui swashbuckle
2个回答
15
投票

你也可以使用SwaggerOperationAttribute

public class UserController : ApiController
{
    [Route("api/user")]
    [SwaggerOperation(Tags = new[] { "User" })]
    IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
    [Route("api/user/resumes")]
    [SwaggerOperation(Tags = new[] { "User" })]
    IHttpActionResult GetResumes() { ... }
}

10
投票

有一种方法 - 尽管没有魔术属性 - 您可以更改swagger启动配置中的默认分组规则,以便引入您自己的自定义属性。

GlobalConfiguration.Configuration 
 .EnableSwagger(c => {
   c.GroupActionsBy(apiDesc => apiDesc
     .GetControllerAndActionAttributes<MethodGroupAttribute>().Any() ?
        apiDesc.GetControllerAndActionAttributes<MethodGroupAttribute()
        .First().GroupName :
        apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName);
 });


/// <summary>
/// Forces method to be displayed within specified group, regardless of controller
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MethodGroupAttribute : Attribute
{
    /// <summary>
    /// Group name
    /// </summary>
    public string GroupName { get; private set; }

    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="groupName"></param>
    public MethodGroupAttribute(string groupName)
    {
        if (string.IsNullOrEmpty(groupName))
        {
            throw new ArgumentNullException("groupName");
        }
        GroupName = groupName;
    }
}

用法:

[Route("api/user")]
[MethodGroup("User")]
IHttpActionResult GetUser() { ... }
© www.soinside.com 2019 - 2024. All rights reserved.