Sam Leach
Sam Leach

Reputation: 12966

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.

Upvotes: 3

Views: 3037

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

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.

Upvotes: 3

Related Questions