从MVC中的Controller方法获取Attribute标签?

Luk*_*oks 3 c# reflection asp.net-mvc

我正在尝试从API控制器获取属性标记,以便我可以看到它在运行时允许的HTTP谓词.从下面的示例代码中,我希望能够获得[HttpGet]标记.

[HttpGet]
public void MyResource()
{
    // Controller logic
}
Run Code Online (Sandbox Code Playgroud)

我目前正在使用System.Reflection它在运行时收集有关我的API的其他信息,但到目前为止,我无法检索[HttpGet标记和其他Http动词标记.我已经尝试了下面的每个解决方案而没有运气:

public void GetControllerMethodHttpAttribute()
{
    MethodInfo controllerMethod = typeof(TestController).GetMethods().First();

    // Solution 1
    var attrs = controllerMethod.Attributes;

    // Solution 2
    var httpAttr = Attribute.GetCustomAttributes(typeof(HttpGetAttribute));

    // Solution 3
    var httpAttr2 = Attribute.GetCustomAttribute(controllerMethod, typeof(HttpGetAttribute));

    // Solution 4
    var httpAttr3 = Attribute.IsDefined(controllerMethod, typeof(HttpGetAttribute));
}
Run Code Online (Sandbox Code Playgroud)

我之前研究过的关于这个主题的所有问题只涉及Custom Attribute tags并从中提取价值,但我找不到任何有关获得框架的信息Attribute tags.

有谁知道如何获得[HttpGet]属性标签?

谢谢!

Nin*_*rry 5

建议的解决方案3和4工作.

你必须注意你引用的是正确的HttpGetAttribute.有一个System.Web.Http.HttpGetAttribute,有一个System.Web.Mvc.HttpGetAttribute.

以下代码列出了ValuesControllerAPI控制器的公共方法,以及有关它们是否具有HttpGet或HttpPost属性的信息.

var methods = typeof(ValuesController).GetMethods();
string infoString = "";

foreach(var method in methods)
{
    // Only public methods that are not constructors
    if(!method.IsConstructor && method.IsPublic)
    {
        // Don't include inherited methods
        if(method.DeclaringType == typeof(ValuesController))
        {

            infoString += method.Name;

            if(Attribute.IsDefined(method, typeof(System.Web.Http.HttpGetAttribute)))
            {
                infoString += " GET ";
            }
            if(Attribute.IsDefined(method, typeof(System.Web.Http.HttpPostAttribute)))
            {
                infoString += " POST ";
            }


            infoString += Environment.NewLine;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要交换System.Web.Http.System.Web.Mvc.当控制器是一个MVC控制器,而不是一个API控制器.