TagActionsBy custom tag or controller name
See original GitHub issueHi,
I was looking for a solution where I could group the actions of one or more controllers under a custom tag. I did a bit of searching round and found this section in the documentation. I dug into it and managed to produce a solution where I assign a custom attribute to controller(s) that I want to be tagged together. I then created an extension method for the ApiDescription class that will either extract the name in my custom attribute or use the name of the controller if the attribute is not present. This has worked, however, it was a little painful getting the name of the controller when my attribute was not present. I ended up having to duplicate some of the code in the ApiDescriptionExtensions class. Ideally, I would have just used the ControllerName
extension method but this has been marked as internal.
I have two questions:
- Is there a reason why the
ControllerName
extension method is marked as internal? If not, would it be possible to make it public? - Is there an alternative approach to what I have done which achieves the same result?
Here is the code that I have produced to achieve this.
public class SwaggerGroupAttribute : Attribute
{
public string GroupName { get; }
public SwaggerGroupAttribute(string groupName)
{
GroupName = groupName;
}
}
public static class ApiDescriptionExtensions
{
public static string GroupBySwaggerGroupAttribute(this ApiDescription api)
{
var groupNameAttribute = (SwaggerGroupAttribute)api.ControllerAttributes().SingleOrDefault(attribute => attribute is SwaggerGroupAttribute);
// ------
// Lifted from ApiDescriptionExtensions
var actionDescriptor = api.GetProperty<ControllerActionDescriptor>();
if (actionDescriptor == null)
{
actionDescriptor = api.ActionDescriptor as ControllerActionDescriptor;
api.SetProperty(actionDescriptor);
}
// ------
return groupNameAttribute != null ? groupNameAttribute.GroupName : actionDescriptor?.ControllerName;
}
}
// In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSwaggerGen(c =>
{
// ...
c.TagActionsBy(api => api.GroupBySwaggerGroupAttribute());
}
}
// ******
// Example usage
[SwaggerGroup(“Grouped”)]
public class GroupedAController : Controller { }
[SwaggerGroup(“Grouped”)]
public class GroupedBController : Controller { }
public class NonGroupedController : Controller { }
public class AnotherController : Controller { }
// This results in three groups on the swagger page
//
// - Grouped
// - NonGrouped
// - Another
Issue Analytics
- State:
- Created 6 years ago
- Reactions:6
- Comments:17 (2 by maintainers)
@domaindrivendev custom tags and tag descriptions (from controller xml docs) do not play well together. do you have any nice workaround in mind where I can link a custom tag to a controller’s description?
Actually, in .net6 I’m using TagsAttribute