jeudi 12 octobre 2017

How do I get the Attribute tag from a Controller Method in MVC?

I'm trying to get the Attribute tag from an API Controller so that I can see what HTTP verb it allows at runtime. From the sample code below, I want to be able to get the [HttpGet] tag.

[HttpGet]
public void MyResource()
{
    // Controller logic
}

I am currently using System.Reflection to gather other information about my API while it is running, but so far I have been unable to retrieve the [HttpGet tag and other Http verb tags. I've tried each of the solutions below with no luck:

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

All of the previous questions that I've researched about this topic only related to Custom Attribute tags and pulling values out of those, but I couldn't find any information about getting the framework-included Attribute tags.

Does anyone know how I can get the [HttpGet] Attribute tag?

Thanks!





Aucun commentaire:

Enregistrer un commentaire