Search code examples
c#asp.net-coreasp.net-core-2.1swashbuckleswashbuckle.aspnetcore

How to implement a Swashbuckle IOperationFilter that processes custom attributes in .NET Core


I have implemented a Swashbuckle.Swagger.IOperationFilter to process custom attributes as described here: https://stackoverflow.com/a/52948376/13087

I now want to do something similar for Swashbuckle.AspNetCore 5.0.0.

It seems that the ApiDescription class does not have the extension method GetControllerAndActionAttributes that was uses in the original implementation. I tried reimplementing it by looking at its source code, but it uses members ApiDescription.ActionDescriptor.ControllerDescriptor and ApiDescription.ActionDescriptor.GetCustomAttributes<TAttribute> that I don't appear to exist for .NET Core.

Can anyone help get me started by showing me how to get hold of custom controller and action attributes from an IOperationFilter?

Update It looks like the .NET Framework implementation has an ActionDescriptor that is actually a ReflectedActionDescriptor. This class has a constructor that takes a MethodInfo, which is used to find the attributes.

But I don't see any way to get a MethodInfo for the .NET Core implementation Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor.


Solution

  • I've found my answer: there's an extension method ApiDescription.TryGetMethodInfo that will get the MethodInfoand hence give access to custom attributes.