7

In ASP.NET 4.x, there is a ReflectedControllerDescriptorclass which resides in System.Web.Mvc. This class provides the descriptor of a controller.

In my previous applications, I used to do this:

var controllerDescriptor = new ReflectedControllerDescriptor(controllerType);

var actions = (from a in controllerDescriptor.GetCanonicalActions()
              let authorize = (AuthorizeAttribute)a.GetCustomAttributes(typeof(AuthorizeAttribute), false).SingleOrDefault()
              select new ControllerNavigationItem
                 {
                    Action = a.ActionName,
                    Controller = a.ControllerDescriptor.ControllerName,
                    Text =a.ActionName.SeperateWords(),
                    Area = GetArea(typeNamespace),
                    Roles = authorize?.Roles.Split(',')
                 }).ToList();

return actions;

The problem is I can't find any equivalent of this class in ASP.NET Core. I came across IActionDescriptorCollectionProviderwhich seems to provide limited details.

The Question

My goal is to write an equivalent code in ASP.NET Core. How do I achieve that?

Your help is really appreciated

1
  • 1
    Perhaps try injecting IActionDescriptorCollectionProvider and using that to retrieve the desired instances of ControllerActionDescriptor as described here Commented Sep 1, 2016 at 17:54

1 Answer 1

13

I came across IActionDescriptorCollectionProvider which seems to provide limited details.

Probably you don't cast ActionDescriptor to ControllerActionDescriptor. Related info is here

My goal is to write an equivalent code in ASP.NET Core. How do I achieve that?

Here is my attempt in ConfigureServices method:

    var provider = services.BuildServiceProvider().GetRequiredService<IActionDescriptorCollectionProvider>();
    var ctrlActions = provider.ActionDescriptors.Items
            .Where(x => (x as ControllerActionDescriptor)
            .ControllerTypeInfo.AsType() == typeof(Home222Controller))
            .ToList();
    foreach (var action in ctrlActions)
    {
         var descriptor = action as ControllerActionDescriptor;
         var controllerName = descriptor.ControllerName;
         var actionName = descriptor.ActionName;
         var areaName = descriptor.ControllerTypeInfo
                .GetCustomAttribute<AreaAttribute>().RouteValue;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.