Get all CustomAttributes from Method and Controller inside IDocumentFilter, swashbuckle asp net core, swagger
Asked Answered
P

1

8

Versions:

  • Project: ASP Net Core 2.1, Web API
  • Packages: Swashbuckle.AspNetCore (4.0.1)

Problem:

I have created one CheckIncludeForOperationFilter class, which inherits from Swashbuckle.AspNetCore.Swagger.IDocumentFilter and implements the only method this interface requires - public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context).

What this class should do?
It should search for IncludeForAttribute. That means I should check if the action in the API has this attribute or the whole controller.

What I have?

public class CheckIncludeForOperationFilter : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {            
        foreach (var apiDescription in context.ApiDescriptions)
        {

        }
    }
}

Here things get interesting when I start the program in debug mode, I can clearly see what the object apiDescription has. And it contains everything that I search. Here are the action attributes:

apiDescription.ActionDescriptor.MethodInfo.CustomAttributes

and all Controller Attributes:

apiDescription.ActionDescriptor.MethodInfo.DeclaringType.CustomAttributes

enter image description here

The thing is, the compiler shows the property MethodInfo in debug, but it is missing when I write it. It is highlighted in red and I don't have access to it:

enter image description here

How can I get all the attributes?

Cheers

Panoptic answered 17/9, 2019 at 13:45 Comment(0)
M
7

You can try this approach:

MethodInfo methodInfo;
var ss = apiDescription.TryGetMethodInfo(out methodInfo);
var controllerFilters = methodInfo.DeclaringType.CustomAttributes;
var actionFilters = methodInfo.DeclaringType.CustomAttributes;

and you will get your custom attributes.

Marrero answered 17/9, 2019 at 14:31 Comment(1)
It looks like this extension method TryGetMethodInfo does not exist in older versions of Swashbuckle. If you're stuck on an old version like me, try ApiDescription.ControllerAttributes() and ApiDescription.ActionAttributes().Thor

© 2022 - 2024 — McMap. All rights reserved.