当前位置 > 首页 > Asp.net

Asp.net web Api源码分析-ParameterBindingAttribute

2012-12-7 16:25:00来源:Asp.net

在前面数据绑定中我们曾提到一个FromUriAttribute类,它 集成于ModelBinderAttribute,而ModelBinderAttribute又继承 ParameterBindingAttribute,ParameterBindingAttribute类就一个空方法没什么实现,这里主要的实现在 ModelBinderAttribute类里面,其主要方法是GetBinding,

 public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
        {
            HttpConfiguration config = parameter.Configuration;
            IModelBinder binder = GetModelBinder(config, parameter.ParameterType);
            IEnumerable<ValueProviderFactory> valueProviderFactories = GetValueProviderFactories(config);


            return new ModelBinderParameterBinding(parameter, binder, valueProviderFactories);
        }

这里的GetModelBinder方法具体实现如下,

 public IModelBinder GetModelBinder(HttpConfiguration configuration, Type modelType)
        {
            if (BinderType == null)
            {
                ModelBinderProvider provider = GetModelBinderProvider(configuration);
                return provider.GetBinder(configuration, modelType);
            }


            // This may create a IModelBinder or a ModelBinderProvider
            object value = GetOrInstantiate(configuration, BinderType);

            Contract.Assert(value != null); // Activator would have thrown

            IModelBinder binder = value as IModelBinder;
            if (binder != null)
            {
                return binder;
            }
            else
            {
                ModelBinderProvider provider = value as ModelBinderProvider;
                if (provider != null)
                {
                    return provider.GetBinder(configuration, modelType);
                }

            }

            Type required = typeof(IModelBinder);
            throw Error.InvalidOperation(SRResources.ValueProviderFactory_Cannot_Create, required.Name, value.GetType().Name, required.Name);
        }

这里的检查BinderType 是否为null,这里首先调用GetModelBinderProvider来获取一个ModelBinderProvider实例,

 public ModelBinderProvider GetModelBinderProvider(HttpConfiguration configuration)
        {
            if (BinderType != null)
            {
                object value = GetOrInstantiate(configuration, BinderType);

                if (value != null)
                {
                    VerifyBinderType(value.GetType());
                    ModelBinderProvider result = (ModelBinderProvider)value;
                    return result;
                }
            }

            // Create default over config
            IEnumerable<ModelBinderProvider> providers = configuration.Services.GetModelBinderProviders();

            if (providers.Count() == 1)
            {
                return providers.First();
            }

            return new CompositeModelBinderProvider(providers);
        },

这你的GetOrInstantiate方法非常简单,根据BinderType直接创建一个实例,创建方法configuration.DependencyResolver.GetService,然后验证实例是否是ModelBinderProvider类型实例,如果不是抛出异常,如果是则直接转化为ModelBinderProvider