1

I have an ASP.Net Web Api controller like this:

public class SomeController : ApiController
{
    public myObject Post([FromUri]string qsVar, [FromBody]yourObject bVar)
    {
        return myObject(qsVar, bVar);
    }
}

I am writing a documentation generator and need to determine if a parameter is [FromUri] or [FromBody] based on it's ParameterInfo.

Type tc = typeof(SomeController);

foreach (MethodInfo m in tc.GetMethods())
{
    foreach (ParameterInfo p in m.GetParameters())
    {
        if (p.isFromBody ???) doThis(); else doThat();
    }
}

How do I determine whether a parameter has a [FromUri] or [FromBody] flag in an ASP.Net Web Api Controller method?

Answer:

bool isFromUri = p.GetCustomAttributes(false)
    .Any(x => x.GetType() == typeof(FromUriAttribute));
Greg
  • 8,574
  • 21
  • 67
  • 109
  • I'd recommend you take a look at the ApiExplorer class: http://blogs.msdn.com/b/yaohuang1/archive/2012/05/13/asp-net-web-api-introducing-iapiexplorer-apiexplorer.aspx. It should give you everything you need to be able to generate documentation. Web API also comes with a help page if that works for you: http://blogs.msdn.com/b/yaohuang1/archive/2012/08/15/introducing-the-asp-net-web-api-help-page-preview.aspx. – Youssef Moussaoui Jul 07 '13 at 18:00
  • thanks @YoussefMoussaoui, I initially looked into that it kinda sucks for a help page. I decided to use Swagger and I needed more control over the process to generate the json that Swagger requires: https://developers.helloreverb.com/swagger/ – Greg Jul 07 '13 at 18:50
  • Hi @Greg please look at my question => http://stackoverflow.com/questions/25206833/list-of-controllers-and-classes-in-asp-net-web-api – Melih Mucuk Aug 08 '14 at 16:15

1 Answers1

0

You may take a look at the CustomAttributes property:

bool hasFromBodyAttribute = p
    .CustomAttributes
    .Any(x => x.AttributeType == typeof(FromBodyAttribute));

if (hasFromBodyAttribute) 
{
    doThis(); 
}
else 
{
    doThat();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928