目录

  1. ModelBinder

  2. ModelBinderProvider

  3. 不同类型的Model绑定

    • 简单类型
    • 复杂类型
    • 其他类型

ModelBinder

ModelBinder是Model绑定的核心.

public interface IModelBinder
{
//绑定Model方法,返回绑定是否成功
bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
}

ModelBindingContext

public class ModelBindingContext
{
//数据源
public IValueProvider ValueProvider { get; set; }
//最终创建的对象 绑定过程就是创建Model
public object Model { get; set; }
//参数名称
public string ModelName { get; set; }
//参数类型
public Type ModelType { get; } //参数元数据
public ModelMetadata ModelMetadata { get; set; }
//属性元数据
public IDictionary<string, ModelMetadata> PropertyMetadata { get; } //存储绑定结果(包括错误信息,ValueProviderResult),该值引用自ApiController的ModelState
public ModelStateDictionary ModelState { get; set; } public bool FallbackToEmptyPrefix { get; set; }
}

当ModelBinder特性的Name(为null),FallbackToEmptyPrefix为True.

FallbackToEmptyPrefix为False时,则必须数据源有前缀才能绑定上.

Web API定义了一系列的ModelBinder,这里先介绍

public class CompositeModelBinder : IModelBinder
{
//IModelBinder 集合
public CompositeModelBinder(params IModelBinder[] binders)
//使用内部ModelBinder进行绑定Model(默认遍历一次,如果FallbackToEmptyPrefix为True,则会有2次遍历机会)
public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
}

ModelBinderProvider

Web API通过ModelBinderProvider创建ModelBinder

public abstract class ModelBinderProvider
{
public abstract IModelBinder GetBinder(HttpConfiguration configuration, Type modelType);
}

Web API中默认注册了一系列的ModelBinderProvider

    this.SetMultiple<ModelBinderProvider>(new ModelBinderProvider[8]
{
(ModelBinderProvider) new TypeConverterModelBinderProvider(),
(ModelBinderProvider) new TypeMatchModelBinderProvider(),
(ModelBinderProvider) new KeyValuePairModelBinderProvider(),
(ModelBinderProvider) new ComplexModelDtoModelBinderProvider(),
(ModelBinderProvider) new ArrayModelBinderProvider(),
(ModelBinderProvider) new DictionaryModelBinderProvider(),
(ModelBinderProvider) new CollectionModelBinderProvider(),
(ModelBinderProvider) new MutableObjectModelBinderProvider()
});

对应的我们先介绍一下

//同样都是组装一批ModelBinderProvider
public sealed class CompositeModelBinderProvider : ModelBinderProvider
{
public CompositeModelBinderProvider(IEnumerable<ModelBinderProvider> providers)
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
}

ModelBinderAttribute除了通过Name设置FallbackToEmptyPrefix,还有个更重要的属性BinderType

public class ModelBinderAttribute : ParameterBindingAttribute
{
public string Name { get; set; }
//用来指定ModelBinder 或 ModelBinderProvider
public Type BinderType { get; set; }
}

不同类型的Model绑定

不同的数据类型,有不同的数据结构.

所以针对他们的绑定机制也是不同的.

简单类型

TypeConverterModelBinder

public sealed class TypeConverterModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
model = valueProviderResult.ConvertTo(bindingContext.ModelType);
bindingContext.Model = model;
return true;
}
}

复杂类型

在介绍复杂类型的Bind前,先介绍一下下面2个类型.

ComplexModelDto包含复杂类型的元数据和绑定结果

public class ComplexModelDto
{
public ComplexModelDto(ModelMetadata modelMetadata, IEnumerable<ModelMetadata> propertyMetadata) public ModelMetadata ModelMetadata { get; private set; }
public Collection<ModelMetadata> PropertyMetadata { get; private set; }
//key 为属性的元数据,value 为绑定结果
public IDictionary<ModelMetadata, ComplexModelDtoResult> Results { get; private set; }
}

ComplexModelDtoResult

public sealed class ComplexModelDtoResult
{
//绑定结果值
public object Model { get; private set; }
//验证信息
public ModelValidationNode ValidationNode { get; private set; }
}

复杂类型的绑定由 MutableObjectModelBinder 和 ComplexModelDtoModelBinder共同完成.

而上面2个类型,实际就是用来在2个ModelBinder间传递的对象

public class MutableObjectModelBinder : IModelBinder
{
public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//类型筛选
if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName) || !MutableObjectModelBinder.CanBindType(bindingContext.ModelType))
return false;
//1. 创建空对象
bindingContext.ModelMetadata.Model = Activator.CreateInstance(bindingContext.ModelType);
//2. 创建ComplexModelDto对象
ComplexModelDto complexModelDto = new ComplexModelDto(bindingContext.ModelMetadata,bindingContext.PropertyMetadata);
//3. 进入绑定流程
this.ProcessDto(actionContext, bindingContext, complexModelDto);
return true;
} internal void ProcessDto(HttpActionContext actionContext, ModelBindingContext bindingContext, ComplexModelDto dto)
{
//创建子ModelBindingContext
var subContext = new ModelBindingContext(bindingContext)
{
ModelName = bindingContext.ModelName,
ModelMetadata = GetMetadata(typeof(ComplexModelDto))
};
//调用ComplexModelDtoModelBinder 对ComplexModelDto进行绑定
actionContext.Bind(subContext); //对复杂类型的属性进行绑定
foreach (var result in (IEnumerable<KeyValuePair<ModelMetadata, ComplexModelDtoResult>>) dto.Results)
{
ModelMetadata key = result.Key;
ComplexModelDtoResult dtoResult = result.Value;
if (dtoResult != null)
{
var property = bindingContext.ModelType.GetProperty(key.PropertyName);
this.SetProperty(actionContext, bindingContext, key, dtoResult,property);
}
}
}
}

ComplexModelDtoModelBinder则将所有属性再通过调度其他的ModelBinder进行绑定.并将结果保存在ComplexModelDto的Results属性中.

其他类型

Web API还提供了其他常用的数据类型 ModelBinder

CollectionModelBinder来实现 集合 类型(指的集合是实现了IEnumerable接口的类型)

ArrayModelBinder来实现 数组 类型

DictionaryModelBinder来实现 字典 类型

通过对应的ModelBinderProvider可以知道对应的ModelBinder 能实现哪种类型的绑定

备注

[Web API] Web API 2 深入系列(7) Model绑定(下)的更多相关文章

  1. [Web API] Web API 2 深入系列(6) Model绑定(上)

    目录 解决什么问题 Model元数据解析 复杂类型 ValueProvider ValueProviderFactory 解决什么问题 Model: Action方法上的参数 Model绑定: 对Ac ...

  2. ASP.NET Web API - ASP.NET MVC 4 系列

           Web API 项目是 Windows 通信接口(Windows Communication Foundation,WCF)团队及其用户激情下的产物,他们想与 HTTP 深度整合.WCF ...

  3. 如何用Baas快速在腾讯云上开发小程序-系列1:搭建API & WEB WebSocket 服务器

    版权声明:本文由贺嘉 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/221059001487422606 来源:腾云阁 h ...

  4. Java web与web gis学习笔记(二)——百度地图API调用

    系列链接: Java web与web gis学习笔记(一)--Tomcat环境搭建 Java web与web gis学习笔记(二)--百度地图API调用 JavaWeb和WebGIS学习笔记(三)-- ...

  5. HTML5权威指南--Web Storage,本地数据库,本地缓存API,Web Sockets API,Geolocation API(简要学习笔记二)

    1.Web Storage HTML5除了Canvas元素之外,还有一个非常重要的功能那就是客户端本地保存数据的Web Storage功能. 以前都是用cookies保存用户名等简单信息.   但是c ...

  6. 初试ASP.NET Web API/MVC API(附Demo)

    写在前面 HTTP RESTful 创建Web API 调用Web API 运行截图及Demo下载 ASP.NET Web API是​​一个框架,可以很容易构建达成了广泛的HTTP服务客户端,包括浏览 ...

  7. 我所理解的RESTful Web API [Web标准篇]

    REST不是一个标准,而是一种软件应用架构风格.基于SOAP的Web服务采用RPC架构,如果说RPC是一种面向操作的架构风格,而REST则是一种面向资源的架构风格.REST是目前业界更为推崇的构建新一 ...

  8. 重构Web Api程序(Api Controller和Entity)续篇

    昨天有写总结<重构Web Api程序(Api Controller和Entity)>http://www.cnblogs.com/insus/p/4350111.html,把一些数据交换的 ...

  9. web api写api接口时返回

    web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法) 找到Global.asax文件,在Applic ...

随机推荐

  1. Java面试查漏补缺

    一.基础 1.&和&&的区别. [概述] &&只能用作逻辑与(and)运算符(具有短路功能):但是&可以作为逻辑与运算符(是“无条件与”,即没有短路的功 ...

  2. 简单的ATM取款过程

    一个简单的ATM的取款过程是这样的:首先提示用户输入密码(pwd),最多只能输3次,超过三次则提示用户“密码已输入三次错误,请取卡.“结束交易.如果用户密码正确,在提示用户输入金额(money),AT ...

  3. SQL Server2016 原生支持JSON

    SQL Server2016 原生支持JSON SQL Server 2005 开始支持 XML 数据类型,提供原生的 XML数据类型.XML 索引以及各种管理 XML 或输出 XML 格式的函数. ...

  4. 在 Windows 上安装Rabbit MQ 指南

    rabbitMQ是一个在AMQP协议标准基础上完整的,可服用的企业消息系统.他遵循Mozilla Public License开源协议.采用 Erlang 实现的工业级的消息队列(MQ)服务器. Ra ...

  5. CI-持续集成(1)-软件工业“流水线”概述

    CI-持续集成(1)-软件工业“流水线”概述 1   概述 持续集成(Continuous integration)是一种软件开发实践,即团队开发成员经常集成它们的工作,通过每个成员每天至少集成一次, ...

  6. 安装 mysql-5.7.5-m15-winx64

    win7 64位下如何安装配置mysql-5.7.5-m15-winx64 距离上次安装MySQL已经过去好久了.步骤这些,有可能会忘记.简单记录一下吧.(参考了一些网络上的博客.) 1.mysql- ...

  7. [变]C#谜题(1-10)表达式篇

    [变]C#谜题(1-10)表达式篇 最近偶然发现了<Java谜题>,很有意思,于是转到C#上研究一下. 本篇是关于表达式的一些内容. 谜题1:奇数性(负数的取模运算) 下面的方法意图确定它 ...

  8. 三国魂破解1——resmask.swf

    这个是资源文件的映射. 根据index.swf的加载流程,直到初始化会加载: 破解方式: var l:URLLoader = new URLLoader(); l.dataFormat = URLLo ...

  9. 《Entity Framework 6 Recipes》中文翻译系列 (16) -----第三章 查询之左连接和在TPH中通过派生类排序

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 3-10应用左连接 问题 你想使用左外连接来合并两个实体的属性. 解决方案 假设你有 ...

  10. 修改注册表 去除Windows快捷方式图标小箭头

    一些朋友不喜欢Windows系统中快捷方式图标上面的小箭头,下面介绍如何修改注册表去除快捷方式图标上的小箭头. 1.开始->运行->输入regedit,启动注册表编辑器,然后; 2.依次展 ...