如何为站点中的所有操作创建操作链接?
我想将这些操作链接放入菜单系统中。
我希望我能做类似的事情
foreach controller in controllers {
foreach action in controller{
stringbuilder.writeline(
"<li>"+actionlink(menu, action, controller)+"<li>"
);
}
}
如何为站点中的所有操作创建操作链接?
我想将这些操作链接放入菜单系统中。
我希望我能做类似的事情
foreach controller in controllers {
foreach action in controller{
stringbuilder.writeline(
"<li>"+actionlink(menu, action, controller)+"<li>"
);
}
}
这是我的看法:
var controllers = Assembly.GetCallingAssembly().GetTypes().Where(type => type.IsSubclassOf(typeof(Controller))).ToList();
var controlList = controllers.Select(controller =>
new
{
Actions = GetActions(controller),
Name = controller.Name,
}).ToList();
方法GetActions
如下:
public static List<String> GetActions(Type controller)
{
// List of links
var items = new List<String>();
// Get a descriptor of this controller
var controllerDesc = new ReflectedControllerDescriptor(controller);
// Look at each action in the controller
foreach (var action in controllerDesc.GetCanonicalActions())
{
// Get any attributes (filters) on the action
var attributes = action.GetCustomAttributes(false);
// Look at each attribute
var validAction =
attributes.All(filter => !(filter is HttpPostAttribute) && !(filter is ChildActionOnlyAttribute));
// Add the action to the list if it's "valid"
if (validAction)
items.Add(action.ActionName);
}
return items;
}
如果您需要菜单系统检查MVC Sitemap Provider,它将根据您在成员资格实施中定义的角色让您绝对控制要呈现的内容。
这是如何从控制器Asp.net Mvc 获取所有操作的方法:列出具有特定属性的控制器上的所有操作或访问 ASP.NET MVC 应用程序中的控制器/操作列表
为了实现您的目标,您应该在您的使用并过滤来自第二个链接的每个控制器调用的Assembly.GetExportedTypes()
子类和子类。ControllerBase
new ReflectedControllerDescriptor(typeof(TController)).GetCanonicalActions()