mattfrear/Swashbuckle.AspNetCore.Filters

Minimal Apis & SetRequestExample

nilzzzzzz opened this issue · 4 comments

Hi,

after upgrading to dotnet 6 rc2 with minimal apis, we run into the issue that an exception is thrown in src/Swashbuckle.AspNetCore.Filters/Examples/ExamplesOperationFilter.cs
SetRequestExamples Line 37 because MethodInfo is null.
This only happens for our minimal api endpoints, the normal controller work fine.

Any idea if this is an issue in this repo or in the general Swashbuckle.AspNetCore Repository?

Best

Nils

Dunno sorry. I stay away from betas and RCs.

There seems to be an issue with this method using minimal apis Swashbuckle.AspNetCore.Filters.Extensions.OperationFilterContextExtensions.GetControllerAndActionAttributes

It's normal that it doesn't work with minimal api since there are no controller and actions :)

A method like this could mitigate the issue.

EndpointMetadata doesn't exist for .NET Standard 2.0

  internal static class OperationFilterContextExtensions
    {
        public static IEnumerable<T> GetMethodAttributes<T>(this OperationFilterContext context) where T : Attribute
        {
            if (context.MethodInfo != null)
            {
                return context.GetControllerAndActionAttributes<T>();
            }
            #if NETCOREAPP3_1_OR_GREATER
            if (context.ApiDescription.ActionDescriptor.EndpointMetadata != null)
            {
                return context.GetEndpointMetadataAttributes<T>();
            }
            #endif
            return new List<T>();
        }

        private static IEnumerable<T> GetControllerAndActionAttributes<T>(this OperationFilterContext context) where T : Attribute
        {
            var controllerAttributes = context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes<T>();
            var actionAttributes = context.MethodInfo.GetCustomAttributes<T>();

            var result = new List<T>(controllerAttributes);
            result.AddRange(actionAttributes);
            return result;
        }

        #if NETCOREAPP3_1_OR_GREATER
        private static IEnumerable<T> GetEndpointMetadataAttributes<T>(this OperationFilterContext context) where T : Attribute
        {
            var endpointAttributes = context.ApiDescription.ActionDescriptor.EndpointMetadata.OfType<T>();

            var result = new List<T>(endpointAttributes);
            return result;
        }
        #endif
    }