Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ControllerDescriptor FindAction returns null

controller:

[HttpDelete]
public ActionResult Delete(int id)
{
}

method:

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

ActionDescriptor is null when an action has [Delete] attribute. Is there a way to get Action Name from controller context?

like image 974
ShaneKm Avatar asked Dec 05 '12 12:12

ShaneKm


1 Answers

I had the same problem in .net 4.5, because the FindAction method only search the get attributes. I resolved the problem adding a second search with the GetCanonicalActions method.

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

Note: I use the linq method FirstOrDefault, so rember add using System.Linq;

like image 119
Juan Carlos Velez Avatar answered Oct 02 '22 23:10

Juan Carlos Velez