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

前端 未结 5 1869
囚心锁ツ
囚心锁ツ 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:31

    By default if I have a controller called ShippingController then the swagger generated UI with name "Shipping"

    I was looking to change the name of my controller to something more friendly or in another language. The best I could find was to use a SwaggerOperation attribute to change the name, but this has the limitation that it is a method level attribute and I dont really want to specify the name on every method.

    So, I created a convention class to use with controller Route attribute, that we usually use on our controllers and then have the swagger use that to be the name of the controller. Well you know there is a name property on the attribute but the generated swagger doesnt seem to use it.

    STEP 1: Create this class:

    When the app starts up it will run this and I will be able to look up the Route attribute on my controllers if they have the attribute specified and then use the name property to change the name of the Controller.

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.ApplicationModels;
    
    namespace RestServices.Configuration.ConfigInstallers.Conventions
    {
        public class ControllerDocumentationConvention : IControllerModelConvention
        {
            void IControllerModelConvention.Apply(ControllerModel controller)
            {
                if (controller == null)
                    return;
    
                foreach (var attribute in controller.Attributes)
                {
                    if (attribute.GetType() == typeof(RouteAttribute))
                    {
                        var routeAttribute = (RouteAttribute)attribute;
                        if (!string.IsNullOrWhiteSpace(routeAttribute.Name))
                            controller.ControllerName = routeAttribute.Name;
                    }
                }
    
            }
        }
    }
    

    STEP 2: Startup.cs:

    Modify the StartUp.cs file and in the configure services we need to register our class in the Conventions list. See below:

    services.AddControllers(o =>
    {
       o.Conventions.Add(new ControllerDocumentationConvention());
    });
    

    STEP 3: In each controller add name property in Route Attribute:

    [ApiController]
    [ApiVersion("1.0")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = "v1")]
    [Route("api/Envios/{version:apiVersion}", Name =  "Envios", Order = 1)]
    [Produces("application/json")]
    public class ShippingController
    

    Now when I run the app and my swagger is generated you can see the controller name is changed to be the same as the text in the route attributes name property.

提交回复
热议问题