是否可以设置行动描述?如果有可能,我该如何获得描述?
示例:
public class TestingController : Controller
{
[Description("Description Test")]
public ActionResult Index()
{
return View();
}
}
答案 0 :(得分:0)
您可以这样做,首先您需要定义一个属性,然后使用反射来提取其信息:
[AttributeUsage(AttributeTargets.All, Inherited = true)]
public class DescriptionAttribute : Attribute
{
private readonly string _title;
public string Title
{
get { return _title; }
}
public DescriptionAttribute(string title)
{
_title = title;
}
}
public static class Extensions
{
public static string GetDisplayName(this MemberInfo target)
{
return target.GetCustomAttributes(typeof(DescriptionAttribute), true)
.Cast<DescriptionAttribute>().Select(d => d.Title)
.SingleOrDefault() ?? target.Name;
}
}
并以这种方式使用它:
public class TestingController : Controller
{
[Description("Description Test")]
public ActionResult Index()
{
return View();
}
}
您可以通过以下方式使用反射提取信息:
var controllers =
typeof (MvcApplication).Assembly.GetTypes()
.Where(typeof (IController).IsAssignableFrom).Where(method => method.IsPublic && method.IsDefined(typeof(DescriptionAttribute), true));