原文地址 https://github.com/NancyFx/Nancy/wiki/Model-binding

数据可以通过多种方式传递给Nancy应用程序,例如作为查询字符串的一部分、作为路由的捕获参数或者请求的正文。手工处理数据一些情况下是可行的,但是有些时候需要更丰富的一致的数据需要使用 model模型),这里Nancy的模型绑定就非常适合。

Nancy只需要一行代码就可以收集来自上面的多种来源数据,包括丰富型的JSON和XML类型请求正文,并且可以将他们转换为指定类型的模型的数据实例。

虽然Nancy自带了一些默认绑定器,但如果你需要支持不同内容类型或者复杂的绑定情况,绑定系统也是很容扩展的,简单的就像包含一个命名空间。

Nancy模型绑定被定义为一个 NancyModule 类型的扩展方法,扩展方法在Nancy.ModelBindin命名空间下添加了 Bind() 和BindTo() 方法:

Foo foo = this.Bind();
var foo = this.Bind<Foo>();
var foo = this.BindTo(instance);

上面三个写法同样的功能,仅仅是完成相同事情的不同方式。前两个Bind()重载将创建一个新的Foo类型并且绑定到它,而BindTo()是绑定到已经存在的实例。


 移除不需要的信息

有时候当你从多个来源向模型填入数据(例如防止‘over posting’***),需要模型绑定中忽略掉一些特定的信息。为了适应这种情况,模型绑定器可以使用一些黑名单属性和选定字段。

var foo = this.Bind<Foo>(f => f.id, f => f.creator, f => f.createddate);

黑名单是一个模型类型的“参数”表达式数组,表达式指定了可以绑定器忽略的模型的名称属性和字段。

或:

var foo = this.Bind<Foo>("id", "creator", "createddate");

黑名单是一个字符串型的“参数”数组,字符串表示被忽略的模型的属性和字段。

当绑定到一个有类型的数组、列表或可枚举类型,黑名单会在把袁术维护在序列中。


绑定配置

使用模型绑定时,可以传递一个BindingConfig 实例用来修改模型绑定器的行为。

下面是一个可用配置选项的列表,由BindingConfig 类型提供。

PropertyDescriptionDefault
BodyOnlyWhether the binder should be happy once it has bound to the request body. In this case, request and context parameters will not be bound to. If there is no body and this option is enabled, no binding will take place at all.false
IgnoreErrorsWhether binding error should be ignored and the binder should continue with the next property or field.false
OverwriteWhether the binder is allowed to overwrite properties and fields that do not have a default value.true

BindingConfig.NoOverwrite 是个快捷方式,可以设置的Overwrite值为false。


反序列化丰富内容的request数据

有些时候你需要发送结构化的数据,例如JSON和XML;然后在请求主体并且绑定模型。Nancy模型绑定器支持正文内容序列化器来提供这些功能

开箱即用地,Nancy提供了两种正文反序列化器,一个是为JSON,另一个为XML。模型绑定器使用Content-Type HTTP头确定应该使用那种反序列化器。

By default, the standard JSON deserializer will be used to deserialize any "json based" content types such as application/jsontext/json and application/vnd....+json. Similarly, the standard XML deserializer will be used for “XML based” content types:application/xmltext/xml and application/vnd....+xml.

As with the other model binders, you can author your own body deserializers and Nancy will automatically detect them and any user defined binders take priority over the built in ones.

NOTE: If you encounter the Nancy.Json.JsonSettings.MaxJsonLength Exceeded error because your payload is too high, change that limit in your Bootstrapper inApplicationStartup to be Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;