asp.net mvc源码分析-Controllerl篇 ControllerDescriptor

在上篇asp.net mvc源码分析-Controllerl篇 TempData数据存储 我们讲到了ActionInvoker.InvokeAction(ControllerContext, actionName) 这句,当时跳过了,现在我们首先来看看ActionInvoker属性的定义吧:

  public IActionInvoker ActionInvoker {
            get {
                if (_actionInvoker == null) {
                    _actionInvoker = CreateActionInvoker();
                }
                return _actionInvoker;
            }
            set {
                _actionInvoker = value;
            }
        }
 protected virtual IActionInvoker CreateActionInvoker() {
            return new ControllerActionInvoker();
        }

和TempDataProvider属性定义一样,大家一定要习惯这些代码啊。

而ControllerActionInvoker的定义也很简单,但是这个类却不简单啊。

让我们来看看你InvokeAction的定义吧:

 public virtual bool InvokeAction(ControllerContext controllerContext, string actionName) {
            if (controllerContext == null) {
                throw new ArgumentNullException("controllerContext");
            }
            if (String.IsNullOrEmpty(actionName)) {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");
            }

            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);
            ActionDescriptor actionDescriptor = FindAction(controllerContext, controllerDescriptor, actionName);
            if (actionDescriptor != null) {
                FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor);

                try {
                    AuthorizationContext authContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);
                    if (authContext.Result != null) {
                        // the auth filter signaled that we should let it short-circuit the request
                        InvokeActionResult(controllerContext, authContext.Result);
                    }
                    else {
                        if (controllerContext.Controller.ValidateRequest) {
                            ValidateRequest(controllerContext);
                        }

                        IDictionary<string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);
                        ActionExecutedContext postActionContext = InvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters);
                        InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters, postActionContext.Result);
                    }
                }
                catch (ThreadAbortException) {
                    // This type of exception occurs as a result of Response.Redirect(), but we special-case so that
                    // the filters don't see this as an error.
                    throw;
                }
                catch (Exception ex) {
                    // something blew up, so execute the exception filters
                    ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);
                    if (!exceptionContext.ExceptionHandled) {
                        throw;
                    }
                    InvokeActionResult(controllerContext, exceptionContext.Result);
                }

                return true;
            }

            // notify controller that no method matched
            return false;
        }
这个方法里面的内容不可能一次讲完的,我们看看  ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);很明显ControllerDescriptor是Controller实例的一个包装类。     protected virtual ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext) {
            Type controllerType = controllerContext.Controller.GetType();
            ControllerDescriptor controllerDescriptor = DescriptorCache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));
            return controllerDescriptor;
        }

从这个方法中,我们可以知道实际返回的是一个ReflectedControllerDescriptor实例,它是ControllerDescriptor的子类,DescriptorCache.GetDescriptor(...)好像是从缓存中获取的啊,让我们证实一下吧,先来看看ControllerDescriptorCache的GetDescriptor方法:

 internal sealed class ControllerDescriptorCache : ReaderWriterCache<Type, ControllerDescriptor> {
        public ControllerDescriptor GetDescriptor(Type controllerType, Func<ControllerDescriptor> creator) {
            return FetchOrCreateItem(controllerType, creator);
        }
    }

FetchOrCreateItem方法很简单,从缓存中获取ControllerDescriptor ,如果没有就创建并加入缓存然后在返回,缓存实现方式其实就是一个字典Dictionary<TKey, TValue>。

现在看看ReflectedControllerDescriptor的够着函数是否有什么特别之处:

  _controllerType = controllerType;
            _selector = new ActionMethodSelector(_controllerType);

怎么又有ActionMethodSelector这个东东啊,其构造函数如下      

  public ActionMethodSelector(Type controllerType) {
            ControllerType = controllerType;
            PopulateLookupTables();
        }

      private void PopulateLookupTables() {
            MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);
            MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);
            AliasedMethods = Array.FindAll(actionMethods, IsMethodDecoratedWithAliasingAttribute);
            NonAliasedMethods = actionMethods.Except(AliasedMethods).ToLookup(method => method.Name, StringComparer.OrdinalIgnoreCase);
        }

这个方法很简单,找出ControllerType的所有实例、共有方法,然后在过滤调不是Action的,最后吧这些Action方法分成两部分,一部分有别名,一部分没有别名。

现在我们已经得到了ControllerDescriptor实例,下面应该来看看ActionDescriptor actionDescriptor = FindAction(controllerContext, controllerDescriptor, actionName);这句代码了;同样我们可以确认ActionDescriptor实际上一个Action的包装类。

  protected virtual ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)这个方法实际上就是调用

ControllerDescriptor类FindAction方法,让我们看看你ReflectedControllerDescriptor的FindAction方法,该方法很简单,组要就2句代码:

   MethodInfo matched = _selector.FindActionMethod(controllerContext, actionName);
return new ReflectedActionDescriptor(matched, actionName, this);

_selector.FindActionMethod(controllerContext, actionName);这句就是找到我们需要Action对应的MethodInfo。

  public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName) {
            List<MethodInfo> methodsMatchingName = GetMatchingAliasedMethods(controllerContext, actionName);
            methodsMatchingName.AddRange(NonAliasedMethods[actionName]);
            List<MethodInfo> finalMethods = RunSelectionFilters(controllerContext, methodsMatchingName);

            switch (finalMethods.Count) {
                case 0:
                    return null;

                case 1:
                    return finalMethods[0];

                default:
                    throw CreateAmbiguousMatchException(finalMethods, actionName);
            }
        }
默认情况下,我们的Action是没有别名的 List<MethodInfo> methodsMatchingName = GetMatchingAliasedMethods(controllerContext, actionName);这句执行后是没有什么结果的,而RunSelectionFilters的实现比较特别

  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) {
                ICollection<ActionMethodSelectorAttribute> attrs = ReflectedAttributeCache.GetActionMethodSelectorAttributes(methodInfo);
                if (attrs.Count == 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;
        }
循环每个MethodInfo,查找它们的自定义的ActionMethodSelectorAttribute特性,如果有只返回验证通过的特性。看到ReflectedAttributeCache.GetActionMethodSelectorAttributes(methodInfo)这样的代码感觉由于缓存有关,
  private static ReadOnlyCollection<TAttribute> GetAttributes<TMemberInfo, TAttribute>(ConcurrentDictionary<TMemberInfo, ReadOnlyCollection<TAttribute>> lookup, TMemberInfo memberInfo)
            where TAttribute : Attribute
            where TMemberInfo : MemberInfo {
            return lookup.GetOrAdd(memberInfo, mi => new ReadOnlyCollection<TAttribute>((TAttribute[])memberInfo.GetCustomAttributes(typeof(TAttribute), inherit: true)));
        }

ReflectedAttributeCache这个类有几个缓存字典:

ConcurrentDictionary<MethodInfo, ReadOnlyCollection<ActionMethodSelectorAttribute>>

ConcurrentDictionary<MethodInfo, ReadOnlyCollection<ActionNameSelectorAttribute>> 

ConcurrentDictionary<MethodInfo, ReadOnlyCollection<FilterAttribute>>

ConcurrentDictionary<Type, ReadOnlyCollection<FilterAttribute>>

默认实现ActionMethodSelectorAttribute类主要有以下几个

AcceptVerbsAttribute
HttpDeleteAttribute
HttpGetAttribute
HttpPostAttribute
HttpPutAttribute
NonActionAttribute

AcceptVerbsAttribute

剩下的就是直接实例一个ReflectedActionDescriptor对象了,这个也没什么特殊,只是里面有一个验证方法

if (validateMethod) {
                string failedMessage = VerifyActionMethodIsCallable(methodInfo);
                if (failedMessage != null) {
                    throw new ArgumentException(failedMessage, "methodInfo");
                }
            }

用来验证该方法是否可以执行,以下几种情况经不会通过,(1)方法是静态方法(2)方法的实例类型不是ControllerBase(3)是否包含泛型参数如 public ActionResult Index<T>()是非法的,但 public ActionResult Index(List<string> aa)是合法(4)参数中不能含有Ref和out。

   这篇文章说的很散,我们需要注意一点微软在mvc里面缓存做的很好了,在前面个将获取ControllerTyper时它是有缓存的,一次读取当前程序集所有的ControllerType,在这里提到了一个DescriptorCache 缓存每次调用的ControllerType->ReflectedControllerDescriptor,而ReflectedControllerDescriptor实例会一次去读该Controller的所有Action方法;这里还有一个ReflectedAttributeCache,缓存每次调用MethodInfo的所有特性(ActionMethodSelectorAttribute、ActionNameSelectorAttribute、FilterAttribute),当然FilterAttribute特性还可以在类上面。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET MVC EasyUI-Tree 是一种用于在ASP.NET MVC应用程序中实现树状结构的开源插件。它基于EasyUI框架,为开发人员提供了一种简单而强大的方式来展示和操作树形数据。 使用ASP.NET MVC EasyUI-Tree可以实现以下功能: 1. 数据展示:可以将树状数据以层级结构展示出来,帮助用户更直观地理解数据之间的关系。 2. 数据操作:可以对树状数据进行增加、编辑和删除等操作,使用户可以方便地对树节点进行维护和管理。 3. 数据筛选:可以通过设置过滤条件实现对树状数据的快速筛选,只显示符合条件的节点。 4. 数据排序:可以对树状数据进行排序,按照特定字段的升序或降序排列。 5. 数据搜索:可以通过关键字搜索来快速定位包含特定内容的节点。 6. 数据导入/导出:可以将树状数据导入到Excel等格式文件中,或者将外部数据导入到树状结构中。 7. 数据异步加载:对于大量数据,可以采用异步加载的方式实现分页加载,提升性能和用户体验。 使用ASP.NET MVC EasyUI-Tree需要进行一些配置和编写代码,但整体来说相对容易上手。它提供了丰富的API和事件以供开发人员自定义和扩展,能够满足不同需求的应用场景。 总而言之,ASP.NET MVC EasyUI-Tree是一个强大而易用的工具,能够帮助开发人员在ASP.NET MVC应用程序中轻松地实现树状结构的展示和操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值