public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { return String.Equals(actionName, Name, StringComparison.OrdinalIgnoreCase); }
ASP.NETMVC 定义了以下7 个基于相应HTTP 方法(GET 、POST 、PUT 、DELETE 、Head 、Options 和Patch) 的ActionMethodSelectorAttribute 类型.当将它们应用到某个Action 方法上时,只有在当前请求的HTTP 方法与之相匹配的状况下目标Action 方法才会被选择。他们的内部也是用AcceptVerbsAttribute 实现的. html
public sealed class HttpGetAttribute : ActionMethodSelectorAttribute { private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Get); public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { return _innerAttribute.IsValidForRequest(controllerContext, methodInfo); } }
[Flags] //指示能够将枚举做为位域(即一组标志)处理。 public enum HttpVerbs { Get = 1 << 0,//移位 Post = 1 << 1, Put = 1 << 2, Delete = 1 << 3, Head = 1 << 4, Patch = 1 << 5, Options = 1 << 6, }
public class AcceptVerbsAttribute : ActionMethodSelectorAttribute { public ICollection<string> Verbs { get; private set; }//支持的请求类型 public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } string incomingVerb = controllerContext.HttpContext.Request.GetHttpMethodOverride(); return Verbs.Contains(incomingVerb, StringComparer.OrdinalIgnoreCase); } }//过滤的方法体
private ActionDescriptorCreator GetActionDescriptorDelegate(MethodInfo entryMethod) { // Does the action return a Task? if (entryMethod.ReturnType != null && typeof(Task).IsAssignableFrom(entryMethod.ReturnType)) { return (actionName, controllerDescriptor) => new TaskAsyncActionDescriptor(entryMethod, actionName, controllerDescriptor); } // Is this the FooAsync() / FooCompleted() pattern? if (IsAsyncSuffixedMethod(entryMethod)) { string completionMethodName = entryMethod.Name.Substring(0, entryMethod.Name.Length - "Async".Length) + "Completed"; MethodInfo completionMethod = GetMethodByName(completionMethodName); if (completionMethod != null) { return (actionName, controllerDescriptor) => new ReflectedAsyncActionDescriptor(entryMethod, completionMethod, actionName, controllerDescriptor); } else { throw Error.AsyncActionMethodSelector_CouldNotFindMethod(completionMethodName, ControllerType); } } // Fallback to synchronous method return (actionName, controllerDescriptor) => new ReflectedActionDescriptor(entryMethod, actionName, controllerDescriptor); }
internal static bool IsPropertyAllowed(string propertyName, string[] includeProperties, string[] excludeProperties) { // We allow a property to be bound if its both in the include list AND not in the exclude list. // An empty include list implies all properties are allowed. // An empty exclude list implies no properties are disallowed. bool includeProperty = (includeProperties == null) || (includeProperties.Length == 0) || includeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase); bool excludeProperty = (excludeProperties != null) && excludeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase); return includeProperty && !excludeProperty; }
Controller 使用的ValueProvider 能够经过定义在ContollerBase 中的ValueProvider 属性进行获取和设置。数组
public interface IValueProvider { bool ContainsPrefix(string prefix); ValueProviderResult GetValue(string key); }
ValueProviderResult RawValue表示提供的原始数据,AttemptedValue表示数据值的字符串表示。ConvertTo进行数据转换异步
public virtual string Get(int index) { ArrayList list = (ArrayList)base.BaseGet(index); return GetAsOneString(list); } private static string GetAsOneString(ArrayList list) { int num = (list != null) ? list.Count : 0; if (num == 1) { return (string)list[0]; } if (num <= 1) { return null; } StringBuilder builder = new StringBuilder((string)list[0]); for (int i = 1; i < num; i++) { builder.Append(','); builder.Append((string)list[i]); } return builder.ToString(); }
经过NameValueCollection ValueProvider 提供的数据源将保存在一个NameValueCollection对象中, DictionaryValueProvider 天然将数据源存放在一个真正的字典对象之中。它们之间的不一样之处在于NameValueCollection 中的元素仅限于字符串,而且不对Key 做惟一性约束(每一个Key对应的是一个存储值的列表):字典中的Key 则是惟一的, Value 也不只仅局限于字符串。 public DictionaryValueProvider(IDictionary<string, TValue> dictionary, CultureInfo culture)ide
public RouteDataValueProvider(ControllerContext controllerContext) : base(controllerContext.RouteData.Values, CultureInfo.InvariantCulture) { }
this.Request.Files类型是HttpFileCollectionBase,元素类型是HttpPostedFileBase函数
当咱们根据当前ControllerContext 构建一个H即FileCollectionValueProvider 的时候,ASP.NETMVC 会从当前HTTP 请求的Files 属性中获取全部的HttpPostedFileBase 对象。多个HttpPostedFileBase 能够共享相同的名称,做为数据源容器的字典将HttpPostedFileBase 的名称做为Key ,具备相同名称的一个或者多个HttpPostedFileBase 对象构成一个数组做为对应的Value 。post
子Action 和普通Action 的不一样之处在于它不能用于响应来自客户端的请求,只是在某个View 中被调用以生成某个部分的HTML.HtmIHelper.Action方法调用指定名称的Action生成相应的Html的代码.ui
做为子Action 方法参数的数据来源与普通Action 方法有所不一样, Model 绑定过程当中具体的数据提供由一个类型为System. Web.Mvc.ChildAction ValueProvider 的对象来完成。this
public ChildActionValueProvider(ControllerContext controllerContext) : base(controllerContext.RouteData.Values, CultureInfo.InvariantCulture) {根据路由数据的Values生成数据容器 }
可是ChildActionValueProvider 的GetValue 方法针对给定的Key 获取的值却并非简单地来源于原始的路由数据,否则ChildActionValueProvider 就和RouteDataValueProvider 没有什么分别了。实际上Chil dActionValueProvider 的GetValue 方法获取的值来源于调用spa
HtmHelper 的扩展方法Action 时,经过参数routeValues 指定的RouteValueDictionary 对象。code
当咱们经过HtmIHelper 的扩展方法Action 调用某个指定的子Action 时,若是参数routeValues 指定的RouteValueDictionary 不为空, HtmIHelper 会据此建立一个DictionaryValueProvider<Object>对象,并将这个对象添加到经过routeValues 参数表示的原始的RouteValueDictionary 对象中,对应的Key 就是Chil dActionValueProvider 的静态属性_ childActionValuesKey 所表示的GUID 。
这个RouteValueDictionary 被进一步封装成表示请求上下文的RequestContext 对象,随后被调子Action 所在的Controller 会在该请求上下文中被激活,在Controller 激活过程当中表示ControllerContext 的ControllerContext 被建立出来,毫无疑问它包含了以前建立的
Route ValueDictionary 对象。当咱们针对当前ControllerContext 建立ChildActionValueProvider的时候,做为数据源的RouteValueDictionary 就是这么一个对象。
当调用ChildActionValueProvider 的GetValue 方法获取指定Key 的值时,实际上它并不会直接根据指定的Key 去获取对应的值,而是根据经过其静态字段_childAction ValuesKey 值去获取对应的DictionaryValueProvider<objec t>对象,而后再调用该对象的GetValue 根据指定的Key 去得到相应的值。代码以下
public override ValueProviderResult GetValue(string key) { if (key == null) { throw new ArgumentNullException("key"); } ValueProviderResult explicitValues = base.GetValue(ChildActionValuesKey); if (explicitValues != null) { DictionaryValueProvider<object> rawExplicitValues = explicitValues.RawValue as DictionaryValueProvider<object>; if (rawExplicitValues != null) { return rawExplicitValues.GetValue(key); } } return null; }
在调用HtmlHelper.Action时,代码以下
internal static void ActionHelper(HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, TextWriter textWriter) { if (htmlHelper == null) { throw new ArgumentNullException("htmlHelper"); } if (String.IsNullOrEmpty(actionName)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName"); } RouteValueDictionary additionalRouteValues = routeValues; routeValues = MergeDictionaries(routeValues, htmlHelper.ViewContext.RouteData.Values); routeValues["action"] = actionName; if (!String.IsNullOrEmpty(controllerName)) { routeValues["controller"] = controllerName; } bool usingAreas; VirtualPathData vpd = htmlHelper.RouteCollection.GetVirtualPathForArea(htmlHelper.ViewContext.RequestContext, null /* name */, routeValues, out usingAreas); if (vpd == null) { throw new InvalidOperationException(MvcResources.Common_NoRouteMatched); } if (usingAreas) { routeValues.Remove("area"); if (additionalRouteValues != null) { additionalRouteValues.Remove("area"); } } if (additionalRouteValues != null) { routeValues[ChildActionValueProvider.ChildActionValuesKey] = new DictionaryValueProvider<object>(additionalRouteValues, CultureInfo.InvariantCulture); } RouteData routeData = CreateRouteData(vpd.Route, routeValues, vpd.DataTokens, htmlHelper.ViewContext); HttpContextBase httpContext = htmlHelper.ViewContext.HttpContext; RequestContext requestContext = new RequestContext(httpContext, routeData); ChildActionMvcHandler handler = new ChildActionMvcHandler(requestContext);//经过这个Handle(继承MVCHandle)去处理请求 httpContext.Server.Execute(HttpHandlerUtil.WrapForServerExecute(handler), textWriter, true /* preserveForm */); }
//System. Web.Mvc. ValueProviderCollection 表示一个元素类型为IValueProvider 的集合,除此以外,它自己也是一个ValueProvider public virtual ValueProviderResult GetValue(string key, bool skipValidation)//循环遍历其中的Provider查找,返回第一个. { return (from provider in this let result = GetValueFromProvider(provider, key, skipValidation) where result != null select result).FirstOrDefault(); }
public override IValueProvider GetValueProvider(ControllerContext controllerContext) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } return new FormValueProvider(controllerContext, _unvalidatedValuesAccessor(controllerContext)); }
public static class ValueProviderFactories { private static readonly ValueProviderFactoryCollection _factories = new ValueProviderFactoryCollection() { new ChildActionValueProviderFactory(), new FormValueProviderFactory(), new JsonValueProviderFactory(), new RouteDataValueProviderFactory(), new QueryStringValueProviderFactory(), new HttpFileCollectionValueProviderFactory(), }; public static ValueProviderFactoryCollection Factories { get { return _factories; } } }
ValueProviderFactoryCollection的方法:返回全部的Provider.他们的顺序决定了使用的优先级.
public IValueProvider GetValueProvider(ControllerContext controllerContext) { var valueProviders = from factory in _serviceResolver.Current let valueProvider = factory.GetValueProvider(controllerContext) where valueProvider != null select valueProvider; return new ValueProviderCollection(valueProviders.ToList()); }
public override IModelBinder Binder { get { IModelBinder binder = ModelBinders.GetBinderFromAttributes(_parameterInfo, () => String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedParameterBindingInfo_MultipleConverterAttributes, _parameterInfo.Name, _parameterInfo.Member)); return binder; } }
private void ReadSettingsFromBindAttribute() { BindAttribute attr = (BindAttribute)Attribute.GetCustomAttribute(_parameterInfo, typeof(BindAttribute)); if (attr == null) { return; } _exclude = new ReadOnlyCollection<string>(AuthorizeAttribute.SplitString(attr.Exclude)); _include = new ReadOnlyCollection<string>(AuthorizeAttribute.SplitString(attr.Include)); _prefix = attr.Prefix; }
public static class ModelBinders { private static readonly ModelBinderDictionary _binders = CreateDefaultBinderDictionary(); public static ModelBinderDictionary Binders { get { return _binders; } } private static ModelBinderDictionary CreateDefaultBinderDictionary() { // We can't add a binder to the HttpPostedFileBase type as an attribute, so we'll just // prepopulate the dictionary as a convenience to users. ModelBinderDictionary binders = new ModelBinderDictionary() { //值会放入innerDictionary { typeof(HttpPostedFileBase), new HttpPostedFileBaseModelBinder() }, { typeof(byte[]), new ByteArrayModelBinder() }, { typeof(Binary), new LinqBinaryModelBinder() }, { typeof(CancellationToken), new CancellationTokenModelBinder() } }; return binders; } } public class ModelBinderDictionary : IDictionary<Type, IModelBinder> { private readonly Dictionary<Type, IModelBinder> _innerDictionary = new Dictionary<Type, IModelBinder>(); private IModelBinder _defaultBinder; private ModelBinderProviderCollection _modelBinderProviders; public ModelBinderDictionary() : this(ModelBinderProviders.BinderProviders) { } }
//查找binder的过程
private IModelBinder GetBinder(Type modelType, IModelBinder fallbackBinder) { // Try to look up a binder for this type. We use this order of precedence: // 1. Binder returned from provider // 2. Binder registered in the global table // 3. Binder attribute defined on the type // 4. Supplied fallback binder //1. IModelBinder binder = _modelBinderProviders.GetBinder(modelType); if (binder != null) { return binder; } //2. if (_innerDictionary.TryGetValue(modelType, out binder)) { return binder; } //3.读取应用在参数类型上的CustomModelBinderAttribute binder = ModelBinders.GetBinderFromAttributes(modelType, () => String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderDictionary_MultipleAttributes, modelType.FullName)); return binder ?? fallbackBinder; }
根据类型查找对应的默认的ModelBinder.最高优先级是,在参数上定义的ModelBindAttribute,其次是上边的三个.书中有错误
能够经过注册对应数据类型的IModelBinder,代码ModelBinders.Binders.Add(typeof(Baz) , new BazModelBinder());
也能够添加Provider 代码ModelBinderProviders.BinderProviders.Add(new MyModelBinderProvider())i
public static ModelBinderProviderCollection BinderProviders
{
get { return _binderProviders; }
}
public class ModelState { private ModelErrorCollection _errors = new ModelErrorCollection(); public ModelErrorCollection Errors { get { return this._errors; } } public ValueProviderResult Value { get; set; } }
protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) { // collect all of the necessary binding properties Type parameterType = parameterDescriptor.ParameterType; IModelBinder binder = GetModelBinder(parameterDescriptor); IValueProvider valueProvider = controllerContext.Controller.ValueProvider; string parameterName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName; Predicate<string> propertyFilter = GetPropertyFilter(parameterDescriptor); // finally, call into the binder ModelBindingContext bindingContext = new ModelBindingContext() { FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType), ModelName = parameterName, ModelState = controllerContext.Controller.ViewData.ModelState, PropertyFilter = propertyFilter, ValueProvider = valueProvider }; object result = binder.BindModel(controllerContext, bindingContext); return result ?? parameterDescriptor.DefaultValue; }
若是没有利用BindAttribute 特性为参数设置一个前缀,默认状况下会将参数名称做为前缀。经过前面的介绍咱们知道,这个前缀会被ValueProvider 用于数据的匹配。若是ValueProvider 经过此前缀找不到匹配的数据,将剔除前缀再次进行数据获取。针对以下定义的Action 方法AddContacts ,在请求数据并不包含基于参数名("foo" 和"bar")前缀的状况下,两个参数最终将被绑定上相同的值。
public class ContactController
public void AddContacts(Contact foo , Contact bar)
反之,若是咱们应用BindAttribute 特性显式地设置了一个前缀,这种去除前缀再次实施Model 绑定的后备机制将不会被采用,是否采用后备Model 绑定策略经过ModelBindingContext 的FallbackToEmptyPrefix 属性来控制。
对于简单数据类型,应该没有这个用法.由于前缀置为空的话,属性名就好是空的了
protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { Type typeToCreate = modelType; // we can understand some collection interfaces, e.g. IList<>, IDictionary<,> if (modelType.IsGenericType) { Type genericTypeDefinition = modelType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(IDictionary<,>)) { typeToCreate = typeof(Dictionary<,>).MakeGenericType(modelType.GetGenericArguments()); } else if (genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>) || genericTypeDefinition == typeof(IList<>)) { typeToCreate = typeof(List<>).MakeGenericType(modelType.GetGenericArguments()); } } // fallback to the type's default constructor return Activator.CreateInstance(typeToCreate); }
list.CopyTo(array, 0);