开发者

How-to figure out if an action method has a HttpPost attributte?

开发者 https://www.devze.com 2023-04-02 06:47 出处:网络
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 ac

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消