2

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?

markf78
  • 597
  • 2
  • 7
  • 25
  • WebApi uses convention over configuration: https://www.c-sharpcorner.com/article/software-design-paradigm-convention-over-configuration/ – smoore4 Jan 16 '19 at 17:58

1 Answers1

4

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
{
}
markf78
  • 597
  • 2
  • 7
  • 25