如何确定action方法是否具有HttpPost属性?

时间:2011-09-05 13:08:18

标签: asp.net-mvc

如何判断一个动作方法是否具有HttpPost属性?例如在动作过滤器中..

3 个答案:

答案 0 :(得分:2)

您可以使用ActionDescriptor.GetCustomAttributes获取应用于该操作的属性。 ActionExecutingContext和ActionExecutedContext都公开了一个名为ActionDescriptor的属性,允许您获取ActionDescriptor类的实例。

答案 1 :(得分:1)

您可以使用反射来查看某个操作是否具有HttpPostAttribute。 假设你的方法类似:

[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
   //my code
} 

你可以用这个来做测试:

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

答案 2 :(得分:1)

我找到的更简单的方法如下:

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

我希望这会有所帮助。

快乐的编码。