c# - 通过 Controller .Net Core 中的 ActionExecutingContext 获取自定义属性

标签 c# .net asp.net-core

这曾经用于早期版本的 .Net。 .net 核心术语中的等价物是什么。现在我收到以下错误:

“ActionDescriptor”不包含“GetCustomAttributes”的定义,并且找不到接受“ActionDescriptor”类型的第一个参数的扩展方法“GetCustomAttributes

public virtual void SetupMetadata(ActionExecutingContext filterContext)
{
    var myAttr = filterContext.ActionDescriptor.GetCustomAttributes(typeof(MyAttribute), false);
    if (myAttr.Length == 1)
        //do something
}

属性定义:

public class MyAttribute : Attribute
{
    private readonly string _parameter;

    public PageTitleAttribute(string parameter)
    {
        _parameter = parameter;
    }

    public string Parameter { get { return _parameter; } }
}

代码用法:

[MyAttribute("Attribute value is set here")]
public ActionResult About()
{
    ViewBag.Message = "Your application description page.";
    return View();
}

最佳答案

希望能帮助到别人,我是这样做的:

var attrib = (filterContext.ActionDescriptor as ControllerActionDescriptor).MethodInfo.GetCustomAttributes<MyAttribute>().FirstOrDefault();

关于c# - 通过 Controller .Net Core 中的 ActionExecutingContext 获取自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41803449/

相关文章:

c# - 自定义 Log4Net 附加程序未正确创建表或存储条目

asp.net-core - 如何在 Razor Pages 中禁用 CSRF 防伪造

c# - Grid.Row 和类似属性如何获得如此出色的 DESIGN TIME 支持?

c# - 带滚动条的控件上的 .NET C# MouseEnter 监听器

.net - 找不到 "Microsoft.NET.CoreRuntime"

c# - 使用依赖于 .NET 6 应用程序中的 NLog 的第三方库

javascript - ASP.NET Core 获取 POST FormData() application/x-www-form-urlencoded

typescript - 为什么 Visual Studio 2019 在我的项目中添加了 <TypeScript Compile Remove/>?

c# - EF4 CTP5 POCO 中的软删除、导航属性

c# - SQL 插入 : Duplicate Key Value Specified?