如果我有以下情况:
MySimpleTestController : ApiController
{
}
是否可以在生成的 API 文档中让控制器名称显示为“My Simple Test”而不是“MySimpleTest”?
我进行了搜索,但主要找到了使用 @Api 注释在 Java 中执行此操作的方法,但我使用的是 C# (.net 4.5.2)。
Here is one way https://stackoverflow.com/questions/37076173/is-there-a-way-change-the-controllers-name-in-the-swagger-ui-page做到这一点,但它需要向控制器中的每个路由添加注释,这会很麻烦,因为我的控制器有很多路由。有没有更好的办法?
我最终是这样做的:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class SwaggerControllerNameAttribute : Attribute
{
public string ControllerName { get; private set; }
public SwaggerControllerNameAttribute(string ctrlrName)
{
if (string.IsNullOrEmpty(ctrlrName))
{
throw new ArgumentNullException("ctrlrName");
}
ControllerName = ctrlrName;
}
}
然后在配置中添加如下代码:
configuration.EnableSwagger(c =>
{
c.GroupActionsBy(apiDesc =>
{
var attribute = apiDesc.GetControllerAndActionAttributes<SwaggerControllerNameAttribute>();
if (attribute.Any())
{
return attribute.First().ControllerName;
}
else
{
return apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName;
}
});
}
然后你可以这样做:
[SwaggerControllerName("My Simple Test")]
public class MySimpleTestController : ApiController
{
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)