Search code examples
c#asp.net-coreminimal-apisasp.net-minimal-apis

Retrieving FromBodyAttribute On Argument from Minimal APi - InvocationContext.Arguments


I am trying to write a c# MinimalApi EndpointFilter validator for ComponentModel DataAnnotations. What I have is working fine when passing in a type to validate against but I am trying to make it a bit more generic to pull the type from the [FromBody] attribute of the InvocationContext. My best try is below but an example call returns null:

var fromBody = invocationContext.Arguments
    .Where(w => Attribute.GetCustomAttribute(w.GetType(), typeof(FromBodyAttribute)) is not null);

I am not sure this is possible but would be happy with any suggestions.


Solution

  • The FromBodyAttribute usually is not applied to the argument type but to the handler function parameter (note that there are some edge cases for example when AsParametersAttribute is used). To analyze the handler function parameters you need to use endpoint filter factory, not the filter:

    app.MapPost("/foo", ([FromBody] SomeType t) => "bar")
        .AddEndpointFilterFactory((filterFactoryContext, next) =>
        {
            var parameters = filterFactoryContext.MethodInfo.GetParameters();
            var bodyParams = parameters
                .Where(pi => pi.GetCustomAttributes<FromBodyAttribute>().Any())
                .ToArray();
            return invocationContext => next(invocationContext); // create filter based on handler parameters
        });
    

    See the Filters in Minimal API apps: Register a filter using an endpoint filter factory doc for more info.