Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attributes on method parameters

Looking at ASP.NET Web Api you can add attributes such as [FromBody] and [FromUri] to method parameters, for example:

public virtual Foo Get([FromUri] Guid id)
public virtual HttpResponseMessage Post([FromBody] Foo foo)

I am also aware of their use in CallerInformation.

I understand what they are doing in this context but I am interested in understanding the design choice resulting in their use.

and also,

Further examples of attributes used on method parameters.

like image 276
Sam Leach Avatar asked Jul 14 '26 14:07

Sam Leach


1 Answers

When ASP.NET invokes these methods, it needs to determine which value goes to which parameter. For each parameter it uses reflection to check for these attributes, which specify the source of the parameter value, giving you control. This is kind of how they do it:

Type myType = typeof(MyType)
MethodInfo method = myType.GetMethod('Post');
foreach (ParameterInfo parameter in method.GetParameters())
{
    if (parameter.IsDefined(typeof(FromUri), false))
    {
        // attempt to find value in uri
    }        
    else if (parameter.IsDefined(typeof(FromPost), false))
    {
        // from post body
    }
    else
    {
        // have to find out myself!
    }
}

I don't think any of the alternatives are as easy and flexible as this one - you could of course have separate configuration files or implement an interface that describes the parameter value source - I think it's nice to have it all defined right there at the method.

Also by passing the request body to the method as parameter, you can unit test your methods without a web environment.

like image 60
C.Evenhuis Avatar answered Jul 16 '26 05:07

C.Evenhuis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!