How-to figure out if an actio开发者_如何学Gon method has a HttpPost attributte ?
For example in the action filter..
You can use ActionDescriptor.GetCustomAttributes to get attributes applied to the action. Both ActionExecutingContext and ActionExecutedContext expose a property called ActionDescriptor allowing you to get an instance of ActionDescriptor class.
you can use reflection to see if an action have the HttpPostAttribute. Assuming your method is something similar:
[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
//my code
}
you can do the test with this:
var controller = GetMyController();
var type = controller.GetType();
var methodInfo = type.GetMethod("MyAction", new Type[1] { typeof(MyViewModel) });
var attributes = methodInfo.GetCustomAttributes(typeof(HttpPostAttribute), true);
Assert.IsTrue(attributes.Any());
The simpler way that I found is the following:
var controller = GetMyController();
var type = controller.GetType();
var methodInfo = type.GetMethod("MyAction", new Type[1] { typeof(MyViewModel) });
bool isHttpGetAttribute = methodInfo.CustomAttributes.Where(x=>x.AttributeType.Name == "HttpGetAttribute").Count() > 0
I hope this helps.
Happy coding.
精彩评论