我一直在努力解决这个问题,我相信我已经提出了一个应该在大多数时间都可以工作的解决方案.它涉及获取有ControllerDescriptor问题的控制器,然后检查每个ActionDescriptor返回的控制器ControllerDescriptor.GetCanonicalActions().
我最终制作了一个动作,在我的控制器中返回了部分视图,但我认为弄清楚发生了什么是相当容易的,所以请随意采取代码并根据需要进行更改.
[ChildActionOnly]
public ActionResult Navigation()
{
// List of links
List<string> NavItems = new List<string>();
// Get a descriptor of this controller
ReflectedControllerDescriptor controllerDesc = new ReflectedControllerDescriptor(this.GetType());
// Look at each action in the controller
foreach (ActionDescriptor action in controllerDesc.GetCanonicalActions())
{
bool validAction = true;
// Get any attributes (filters) on the action
object[] attributes = action.GetCustomAttributes(false);
// Look at each attribute
foreach (object filter in attributes)
{
// Can we navigate to the action?
if (filter is HttpPostAttribute || filter is ChildActionOnlyAttribute)
{
validAction = false;
break;
}
}
// Add the action to the list if it's "valid"
if (validAction)
NavItems.Add(action.ActionName);
}
return PartialView(NavItems);
}
Run Code Online (Sandbox Code Playgroud)
可能有更多的过滤器需要注意,但现在这符合我的需求.