如何在ASP.NET Core RC2中获取控制器的自定义属性 [英] How to get custom attributes for a controller in asp.net core rc2

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

问题描述

我已经创建了一个自定义属性:

I have created a custom attribute :

[AttributeUsage(AttributeTargets.Method| AttributeTargets.Class)]
public class ActionAttribute : ActionFilterAttribute
{
    public int Id { get; set; }
    public string Work { get; set; }
}

我的控制器:

[Area("Administrator")]
[Action(Id = 100, Work = "Test")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

我的代码:我使用反射来查找当前程序集中的所有Controller

my code : i use reflection to find all Controllers in the current assembly

 Assembly.GetEntryAssembly()
         .GetTypes()
         .AsEnumerable()
         .Where(type => typeof(Controller).IsAssignableFrom(type))
         .ToList()
         .ForEach(d =>
         {
             // how to get ActionAttribute ?
         });

是否可以务实地读取所有ActionAttribute?

is it possible to read all the ActionAttribute pragmatically?

推荐答案

要从类中获取属性,您可以执行以下操作:

To get an attributes from the class you can do something the following:

typeof(youClass).GetCustomAttributes<YourAttribute>();
// or
// if you need only one attribute
typeof(youClass).GetCustomAttribute<YourAttribute>();

它将返回IEnumerable<YourAttribute>.

因此,在您的代码中,它将类似于:

So, within your code it will be something like:

Assembly.GetEntryAssembly()
        .GetTypes()
        .AsEnumerable()
        .Where(type => typeof(Controller).IsAssignableFrom(type))
        .ToList()
        .ForEach(d =>
        {
            var yourAttributes = d.GetCustomAttributes<YourAttribute>();
            // do the stuff
        });

对于CoreCLR,您需要再调用一个方法,因为API有所更改:

In case with CoreCLR you need to call one more method, because the API has been changed a bit:

typeof(youClass).GetTypeInfo().GetCustomAttributes<YourAttribute>();

这篇关于如何在ASP.NET Core RC2中获取控制器的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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