Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get custom attributes via ActionExecutingContext from controller .Net Core

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

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

Attribute definition:

public class MyAttribute : Attribute
{
    private readonly string _parameter;

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

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

Code Usage:

[MyAttribute("Attribute value is set here")]
public ActionResult About()
{
    ViewBag.Message = "Your application description page.";
    return View();
}
like image 228
user869375 Avatar asked Jan 23 '17 09:01

user869375


1 Answers

For ASP.NET Core 3+:

    var filters = context.Filters;
    // And filter it like this: 
    var filtered = filters.OfType<OurFilterType>();

like image 144
Rodion Mostovoy Avatar answered Sep 19 '22 02:09

Rodion Mostovoy