通过ActionExecutingContext从控制器.Net Core获取自定义属性 [英] Get custom attributes via ActionExecutingContext from controller .Net Core

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

问题描述

这曾经与.Net的早期版本一起使用..net核心术语等效于什么.现在出现以下错误:

This used used to work with earlier version of .Net. What's the equivalent in .net core terms. Now I get following error:

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

'ActionDescriptor' does not contain a definition for 'GetCustomAttributes' and no extension method 'GetCustomAttributes' accepting a first argument of type 'ActionDescriptor' could be found

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

推荐答案

希望帮助别人,这就是我所做的:

Hope to help others, here's what i did:

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

这篇关于通过ActionExecutingContext从控制器.Net Core获取自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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