Getting Controller details in ASP.NET Core

不问归期 提交于 2019-12-11 04:07:33

问题


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:


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


来源:https://stackoverflow.com/questions/39276763/getting-controller-details-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!