在 MVC 上设置描述属性
Set description attribute in action on MVC
是否可以设置动作描述?如果可能的话,我怎样才能得到描述?
示例:
public class TestingController : Controller
{
[Description("Description Test")]
public ActionResult Index()
{
return View();
}
}
你可以这样做,首先你需要定义一个属性然后使用反射来提取它的信息:
[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));
是否可以设置动作描述?如果可能的话,我怎样才能得到描述?
示例:
public class TestingController : Controller
{
[Description("Description Test")]
public ActionResult Index()
{
return View();
}
}
你可以这样做,首先你需要定义一个属性然后使用反射来提取它的信息:
[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));