我有控制器喜欢
public class UserController : ApiController
{
[Route("api/user")]
IHttpActionResult GetUser() { ... }
}
public class ResumeController : ApiController
{
[Route("api/user/resumes")]
IHttpActionResult GetResumes() { ... }
}
有没有办法(除了通过推出自己的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() { ... }
}
你也可以使用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() { ... }
}
有一种方法 - 尽管没有魔术属性 - 您可以更改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() { ... }