Is there a way change the Controller's name in the swagger-ui page?

前端 未结 5 1876
囚心锁ツ
囚心锁ツ 2021-02-18 20:03

I\'m using Swashbuckle to enable the use of swagger and swagger-ui in my WebApi project.

In the following image you can see two of my controllers shown in the swagger-ui

5条回答
  •  余生分开走
    2021-02-18 20:09

    I tried using venerik's answer, but it still kept the original controller name in the UI along with the new tag that you specify. I also didn't like that you had to add an attribute to every function, so I came up with a solution where you only have to add an attribute to the controller. There are two steps:

    Add DisplayNameAttribute on the controller:

    [DisplayName("Your New Tag")]
    public class YourController : ApiController
    {
        // ...
    }
    

    Then in the Swagger configuration, you can override the base functionality using the GroupActionsBy function to pull the name that you specified in that attribute:

    GlobalConfiguration.Configuration
        .EnableSwagger(c => {
    
            c.GroupActionsBy(apiDesc => {
                var attr = apiDesc
                    .GetControllerAndActionAttributes()
                    .FirstOrDefault();
    
                // use controller name if the attribute isn't specified
                return attr?.DisplayName ?? apiDesc.ControllerName(); 
            });
    
        })
        .EnableSwaggerUi(c => {
            // your UI config here
        });
    

    ControllerName() is an extension method defined in the Swagger-Net library. If you aren't using that you can also get the controller name from apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName

提交回复
热议问题