Search code examples
c#asp.net.netasp.net-mvcaction-filter

How can I get the function/action name that custom attribute is attached to while it is executing?


Ideally, I want to create a filter that inherits from ActionFilterAttribute that I can apply in Global.asax that will create performance counters for all the actions in my application. That problem is easy, but the issue is that I want the performance counters to have the method signature of the action that they are attached to in their name. However, I can't find a way to extract the method name of the method that an attribute is attached to during construction. This is causing me to have to apply the attributes to each action individually and pass in their signature as a parameter. However, this poses obvious problems (i.e. updates to method signature not automatically synchronized with perf counter naming).

To simplify the problem, if I attach an attribute to a method of any kind, can I access the name/signature of the method that it is attached to? I'm looking for a generic solution that works for attributes that don't derive from ActionFilterAttribute also.

public class SomeAttribute : ActionFilterAttribute
{
    public string FunctionSignature { get; set; }

    public SomeAttribute() 
    {
        this.FunctionName = { HOW DO I GET THE NAME OF THE METHOD I'M ON WITHOUT PASSING IT IN AS AN INPUT ARGUMENT? }
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Some code to update perf counter(s) with recorded time that will use string.Format("{0}: Avg. Time or Something", this.FunctionSignature).
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    {
        // Some code to record time.
    }
}

[SomeAttribute]
public void SomeMethod()
{
    // Some code.
}

Solution

  • Find the name of executing action:

    var actionName = filterContext.ActionDescriptor.ActionName;
    

    or alternatively

    var actionName = filterContext.RouteData.Values["action"] as string
    

    Find parameters (Name, Type, DefaultValue):

    var parameters = filterContext.ActionDescriptor.GetParameters();
    

    Find parameters values:

     var value= filterContext.ActionParameters["parameterName"];