Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Controller details in ASP.NET Core

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

like image 787
Shittu Joseph Olugbenga Avatar asked Mar 11 '23 06:03

Shittu Joseph Olugbenga


1 Answers

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;
    }
like image 53
adem caglin Avatar answered Mar 23 '23 08:03

adem caglin