在ASP.NET Core中获取控制器详细信息 [英] Getting Controller details in ASP.NET Core

查看:618
本文介绍了在ASP.NET Core中获取控制器详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET 4.x中,有一个ReflectedControllerDescriptor类驻留在System.Web.Mvc中.此类提供控制器的描述符.

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;

问题是我在ASP.NET Core中找不到此类的等效项.我碰到了IActionDescriptorCollectionProvider,它似乎提供了有限的详细信息.

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.

问题

我的目标是在ASP.NET Core中编写等效的代码.我该如何实现?

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

非常感谢您的帮助

推荐答案

我遇到了IActionDescriptorCollectionProvider,它似乎 提供有限的详细信息.

I came across IActionDescriptorCollectionProvider which seems to provide limited details.

可能您没有将ActionDescriptor强制转换为ControllerActionDescriptor.相关信息在此处

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

我的目标是在ASP.NET Core中编写等效的代码.我如何能 实现吗?

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

这是我尝试的ConfigureServices方法:

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

这篇关于在ASP.NET Core中获取控制器详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆