dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.58k stars 10.06k forks source link

Services injected with attribute derived from FromKeyedServicesAttribute appear as request body in swagger #58739

Open stevendarby opened 4 weeks ago

stevendarby commented 4 weeks ago

Is there an existing issue for this?

Describe the bug

This is much like #50704 except for attributes derived from FromKeyedServicesAttribute. The fix for the previous issue only checked if the type was exactly FromKeyedServicesAttribute.

Expected Behavior

I'm hoping this could be changed to use something like IsAssignableTo/From so that it covers derived attributes too.

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

No response

Anything else?

Is there a workaround? e.g. some other "Ignore this" attribute I could apply to hide it?

stevendarby commented 4 weeks ago

P.S. I'd be happy to raise a PR if that would help its chances of getting into a 9.0.x release.

stevendarby commented 4 weeks ago

Workaround for swashbuckle, which works with the limited cases I have, but might not be generally applicable for everyone:

public class KeyedServicesFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.ApiDescription.HttpMethod != HttpMethods.Get)
        {
            return;
        }

        var parameter = context.MethodInfo
            .GetParameters()
            .FirstOrDefault(p => p.CustomAttributes.Any(c => c.AttributeType.IsAssignableTo(typeof(FromKeyedServicesAttribute))));

        if (parameter is not null)
        {
            operation.RequestBody = null;

            if (context.SchemaRepository.TryLookupByType(parameter.ParameterType, out var schema))
            {
                context.SchemaRepository.Schemas.Remove(schema.Reference.Id);
            }
        }
    }
}