coolwolf / 27/09/2018

MVC’de Controller açıklamaları eklemek ve bu açıklamaları listelemek

Controller adının üzerine Description attribute ekliyoruz:

[Description("Benim Çok Çalışan Kontrollerim")]
public class MyController : Controller
{
}

ardından uygulamamızdaki tüm controller’leri ve içlerindeki metodları listelemek için aşağıdaki fonksiyonu kullanabiliriz:
 

Assembly assembly = Assembly.GetExecutingAssembly();
IEnumerable types = assembly.GetTypes().Where(type => typeof(Controller).IsAssignableFrom(type)).OrderBy(x => x.Name);
List _controllers = new List();
List _methods = new List();
foreach (Type cls in types)
{
	AttributeCollection attributes =TypeDescriptor.GetProperties(this)[cls.Name].Attributes;
	DescriptionAttribute myAttribute = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
	_controllers.Add(new SelectListItem() { Text= myAttribute.Description, Value= cls.Name.Replace("Controller", "") });
	IEnumerable memberInfo = cls.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public).Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any()).OrderBy(x => x.Name);
	foreach (MemberInfo method in memberInfo)
	{
		if (method.ReflectedType.IsPublic && !method.IsDefined(typeof(NonActionAttribute)))
		{
			_methods.Add(new SelectListItem() { Text=method.Name.ToString() });
		}
	}
}