微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – ASP.NET MVC:获取所有控制器

是否可以让ControllerFactory的所有控制器可用?
我想要做的是在应用程序中获取所有控制器类型的列表,但是以一致的方式.

所以我得到的所有控制器是认请求分辨率正在使用的相同的.

(实际的任务是找到具有给定属性的所有动作方法).

解决方法

您可以使用反射枚举程序集中的所有类,并仅过滤继承自Controller类的类.

最好的参考是asp.net mvc source code.看看ControllerTypeCacheActionMethodSelector类的实现.
ControllerTypeCache显示如何获取所有控制器类.

internal static bool IsControllerType(Type t) {
            return
                t != null &&
                t.IsPublic &&
                t.Name.EndsWith("Controller",StringComparison.OrdinalIgnoreCase) &&
                !t.IsAbstract &&
                typeof(IController).IsAssignableFrom(t);
        }

 public void EnsureInitialized(IBuildManager buildManager) {
            if (_cache == null) {
                lock (_lockObj) {
                    if (_cache == null) {
                        List<Type> controllerTypes = GetAllControllerTypes(buildManager);
                        var groupedByName = controllerTypes.GroupBy(
                            t => t.Name.Substring(0,t.Name.Length - "Controller".Length),StringComparer.OrdinalIgnoreCase);
                        _cache = groupedByName.ToDictionary(
                            g => g.Key,g => g.ToLookup(t => t.Namespace ?? String.Empty,StringComparer.OrdinalIgnoreCase),StringComparer.OrdinalIgnoreCase);
                    }
                }
            }
        }

ActionMethodSelector显示如何检查方法是否具有所需属性.

private static List<MethodInfo> RunSelectionFilters(ControllerContext controllerContext,List<MethodInfo> methodInfos) {
            // remove all methods which are opting out of this request
            // to opt out,at least one attribute defined on the method must return false

            List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();
            List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>();

            foreach (MethodInfo methodInfo in methodInfos) {
                ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute),true /* inherit */);
                if (attrs.Length == 0) {
                    matchesWithoutSelectionAttributes.Add(methodInfo);
                }
                else if (attrs.All(attr => attr.IsValidForRequest(controllerContext,methodInfo))) {
                    matchesWithSelectionAttributes.Add(methodInfo);
                }
            }

            // if a matching action method had a selection attribute,consider it more specific than a matching action method
            // without a selection attribute
            return (matchesWithSelectionAttributes.Count > 0) ? matchesWithSelectionAttributes : matchesWithoutSelectionAttributes;
        }

原文地址:https://www.jb51.cc/aspnet/250628.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐