在Web API控制器方法中从ParameterInfo确定参数位置

时间:2013-07-07 17:54:32

标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-4.0

我有一个像这样的ASP.Net Web Api控制器:

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

我正在编写文档生成器,需要根据它[FromUri]来确定参数是[FromBody]还是ParameterInfo

Type tc = typeof(SomeController);

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

如何确定参数在ASP.Net Web Api控制器方法中是否具有[FromUri][FromBody]标志?

答案:

bool isFromUri = p.GetCustomAttributes(false)
    .Any(x => x.GetType() == typeof(FromUriAttribute));

1 个答案:

答案 0 :(得分:0)

您可以查看CustomAttributes属性:

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

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