I want to get a MethodInfo object from the calling method to determine if there is a special attribute set on that method.
The Programm class with the calling method Run()
class Program
{
private static RestHandler _handler = new RestHandler();
static void Main(string[] args)
{
Run();
}
[Rest("GET")]
static void Run()
{
_handler.Handler(typeof(Program));
}
}
The Class where I would like to determine the custom attribute
public class RestHandler
{
public void Handler(Type t)
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
var attributes = methodInfo.GetCustomAttributes<RestAttribute>();
}
}
The attribute class
public class RestAttribute : Attribute
{
public RestAttribute(string method)
{
Method = method;
}
public string Method { get; set; }
}
My problem here is that the MethodInfo object (methodInfo) is always null even the method object from the stack frame ist set correctly.
The property method.Name returns the correct name of the calling method.
Why the methodInfo object is always null?
This is a private method:
static void Run()
Add BindingFlags.NonPublic to access it via reflection
MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With