0

I want to create friendly names for all action methods.

[LogActionFilter]
    public class ServiceController : ApiController
    {
    [DisplayName("User log in")]
            public object Login()        
            {
                //my logic for login and returns object 
            }
    }

In action filter attribute, I want to get display name of this action.

public class LogActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var actionName = actionContext.Request.RequestUri.AbsolutePath.Split('/').Last();
            //var actionFriendlyName = getDisplayName(actionName); How to get display name?
        }
    }

How can I get the value of DisplayName attribute?

Irfan Y
  • 1,242
  • 2
  • 21
  • 68
  • why down voted? Please brief. – Irfan Y Jul 04 '18 at 09:45
  • 2
    You can use reflection (refer [this Q/A](https://stackoverflow.com/questions/6637679/reflection-get-attribute-name-and-value-on-property) for an example). But its not clear what your trying to do here or how you would use that. –  Jul 04 '18 at 09:51
  • @IrfanYusanif I didn't downvote but if you hover over the downvote button on any question it explains the reasons for which downvotes should be given. Anyway, why do you want to get this name, what do you intend to do with it within your action filter? It's not clear what the purpose would be. Also, these data annotations are intended to be used on fields (i.e. properties of a class), not methods. – ADyson Jul 04 '18 at 10:10

1 Answers1

0

I used this function to get attribute for a method:

public static T GetAttributeFrom<T>(object instance, string    propertyName) where T : Attribute
           {
               var attrType = typeof(T);
               var property = instance.GetType().GetMethod(propertyName);
               return (T)property.GetCustomAttributes(attrType, false).First();
           }

usage:

var actionName = actionContext.Request.RequestUri.AbsolutePath.Split('/').Last();
var displayNameAttribute = GetAttributeFrom<DisplayNameAttribute>(new ServiceController(), actionName);
var methodFriendlyName = displayNameAttribute.DisplayName;
Irfan Y
  • 1,242
  • 2
  • 21
  • 68