简体   繁体   中英

Determine Parameter Location From ParameterInfo In Web API Controller Method

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));

You may take a look at the CustomAttributes property:

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

if (hasFromBodyAttribute) 
{
    doThis(); 
}
else 
{
    doThat();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM