操作方法mvc

时间:2018-07-04 09:40:06

标签: asp.net-mvc data-annotations

我想为所有操作方法创建友好名称。

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

在动作过滤器属性中,我想获取此动作的显示名称。

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

如何获取DisplayName属性的值?

1 个答案:

答案 0 :(得分:0)

我使用此函数获取方法的属性:

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

用法:

var actionName = actionContext.Request.RequestUri.AbsolutePath.Split('/').Last();
var displayNameAttribute = GetAttributeFrom<DisplayNameAttribute>(new ServiceController(), actionName);
var methodFriendlyName = displayNameAttribute.DisplayName;