控制器:
[HttpDelete]
public ActionResult Delete(int id)
{
}
方法:
ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName)
? htmlHelper.ViewContext.Controller
: GetControllerByName(htmlHelper, controllerName);
var controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo);
var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType());
ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);
当操作具有[Delete]属性时,ActionDescriptor为null。有没有办法从控制器上下文中获取Action Name?
答案 0 :(得分:12)
我在.net 4.5中遇到了同样的问题,因为FindAction方法只搜索get属性。我解决了使用GetCanonicalActions方法添加第二次搜索的问题。
ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName)
? htmlHelper.ViewContext.Controller
: GetControllerByName(htmlHelper, controllerName);
var controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo);
var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType());
var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);
//add the following lines
if (actionDescriptor == null)
{
actionDescriptor = controllerDescriptor.GetCanonicalActions().FirstOrDefault(a => a.ActionName == actionName);
}
注意:我使用linq方法FirstOrDefault,因此rember add using System.Linq
;