Asp.net mvc 如何确定操作方法是否具有HttpPost属性?

Asp.net mvc 如何确定操作方法是否具有HttpPost属性?,asp.net-mvc,Asp.net Mvc,如何确定操作方法是否具有HttpPost属性 例如,在动作过滤器中,可以使用获取应用于动作的属性。ActionExecutingContext和ActionExecutedContext都公开了一个名为ActionDescriptor的属性,允许您获取ActionDescriptor类的实例。您可以使用反射来查看某个操作是否具有HttpPostAttribute。 假设您的方法类似: [HttpPost] public ActionResult MyAction(MyViewModel mode

如何确定操作方法是否具有HttpPost属性


例如,在动作过滤器中,可以使用获取应用于动作的属性。ActionExecutingContext和ActionExecutedContext都公开了一个名为ActionDescriptor的属性,允许您获取ActionDescriptor类的实例。

您可以使用反射来查看某个操作是否具有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());

我发现的更简单的方法如下:

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
我希望这有帮助

快乐编码