如何在 swagger-ui 中更改控制器的名称?
How to change controller's name in swagger-ui?
如果我有以下情况:
MySimpleTestController : ApiController
{
}
是否可以在生成的 API 文档中将控制器名称显示为 "My Simple Test" 而不是 "MySimpleTest"?
我进行了搜索,但我主要是在 Java 中找到了使用 @Api 注释进行搜索的方法,但我使用的是 C# (.net 4.5.2)。
这里 可以做到这一点,但它需要为控制器中的每条路由添加注释,这会很麻烦,因为我的控制器有很多路由。有没有更好的方法?
这是我最终的做法:
[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
{
}
如果我有以下情况:
MySimpleTestController : ApiController
{
}
是否可以在生成的 API 文档中将控制器名称显示为 "My Simple Test" 而不是 "MySimpleTest"?
我进行了搜索,但我主要是在 Java 中找到了使用 @Api 注释进行搜索的方法,但我使用的是 C# (.net 4.5.2)。
这里
这是我最终的做法:
[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
{
}