Recently I was creating a WebAPI using .net core and one of the things that is a pain is that when you run the api and look at your swagger the names of the controllers arent very friendly. By default if I have a controller called UserAppointmentsController then the swagger generated will look like the below picture.
The class definition which gives me this looks like the below.
Now Im sure someone will tell me there is an easier way to do this, but when I was looking to try and change the name of my controller to something more friendly 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. What I want to do is have a name property on the 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. Lets imagine I modify my controller to look like the below.
Well unfortunately I couldnt find an article out there which showed how to do this, even thought there seems to be related posts where people are asking how to do it, but it always seems to fall back to the SwaggerOperation attribute on the methods. I found a way to do it so sharing and hopefully its useful to someone. To do this I use a class which implements IControllerModelConvention and add the below code.
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.
Next up we need to modify the StartUp.cs file and in the configure services we need to register our class in the Conventions list. See below
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.
Once I worked out how to do this it was pretty straightforward and hopefully this will be useful to someone trying to do the same thing.