简体   繁体   中英

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

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?

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
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM