gpt4 book ai didi

asp.net-mvc - 如何从 Controller 获取所有 Action 名称

转载 作者:行者123 更新时间:2023-12-04 02:31:28 24 4
gpt4 key购买 nike

如何编写代码以从 asp.net MVC 中的 Controller 获取所有操作名称?

我想自动列出 Controller 中的所有 Action 名称。

有谁知道如何做到这一点?

非常感谢。

最佳答案

我一直在与这个问题搏斗一段时间,我相信我已经想出了一个在大多数情况下都应该有效的解决方案。它涉及获得 ControllerDescriptor对于有问题的 Controller ,然后检查每个 ActionDescriptor返回者 ControllerDescriptor.GetCanonicalActions() .

我最终在我的 Controller 中做了一个返回部分 View 的操作,但我认为弄清楚发生了什么很容易,所以请随意获取代码并根据您的需要进行更改。

[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);
}

可能还有更多过滤器需要注意,但现在这适合我的需求。

关于asp.net-mvc - 如何从 Controller 获取所有 Action 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1638541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com