How to change controller's name in swagger-ui?

↘锁芯ラ 提交于 2020-01-14 06:49:08

问题


if I have the following:

MySimpleTestController : ApiController
{
}

Is it possible to have the controller name appear as "My Simple Test" instead of "MySimpleTest" in the generated API docs?

I did a search but I mostly found ways to do it in Java using an @Api annotation but I am using C# (.net 4.5.2).

Here is one way to do it but it requires adding an annotation to every single route in the Controller which would be cumbersome as my controller has many routes. Is there a better way?


回答1:


Here's how I ended up doing it:

[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;
    }
}

And then add the following code to the configuration:

configuration.EnableSwagger(c =>
{
     c.GroupActionsBy(apiDesc =>
     {
          var attribute = apiDesc.GetControllerAndActionAttributes<SwaggerControllerNameAttribute>();
          if (attribute.Any())
          {
               return attribute.First().ControllerName;
          }
          else
          {
               return apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName;
          }
     });        
}

And then you can do this:

[SwaggerControllerName("My Simple Test")]
public class MySimpleTestController : ApiController
{
}


来源:https://stackoverflow.com/questions/54222584/how-to-change-controllers-name-in-swagger-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!