NancyFx -部分绑定
本文关键字:绑定 -部 NancyFx | 更新日期: 2023-09-27 18:08:26
我正试图实现一种部分更新与NancyFx。
我有一个名为Resource
的类,像这样:
public class Resource
{
public int Id { get; set; }
public decimal SomeValue { get; set; }
public bool Enabled { get; set; }
public DateTime CreationDate { get; set; }
}
我的当前资源实例包含以下值:
{
"Id" : 123,
"SomeValue" : 6,
"Enabled" : true,
"CreationDate" : "2015-08-01T13:00:00"
}
我希望我的PUT方法接收一个仅代表Resource
的一些属性的JSON,例如:
{
"Id": 123,
"SomeValue" : 54.34
}
然后,我将做一个BindTo(myCurrentResourceInstance)
,结果将是:
{
"Id" : 123,
"SomeValue" : 54.34,
"Enabled" : true,
"CreationDate" : "2015-08-01T13:00:00"
}
然而,我得到这个:
{
"Id" : 123,
"SomeValue" : 54.34,
"Enabled" : false,
"CreationDate" : "0001-01-01T00:00:00"
}
JSON中包含的属性适当地覆盖当前实例中的属性,但是BindTo()
方法也改变了我没有在JSON中指定的属性。我想只覆盖JSON中指定的属性;
BindTo()
接收一个BindingConfig
作为参数,它有一个Overwrite
属性(https://github.com/NancyFx/Nancy/wiki/Model-binding)。当此属性为true时,它会导致BindTo()
覆盖所有属性;为false时,不覆盖。
有什么方法可以实现我想要的吗?
谢谢
由于您想要防止当前值在未在JSON中指定时被默认值覆盖,因此您可以使用以下命令将未定义的值列入黑名单:
BindTo<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties)` extension method
有了这个,我们可以通过反射提取属性列表,并排除在JSON上定义的属性列表,并将其传递给该方法:
var definedProperties = JsonConvert
.DeserializeObject<JObject>(json)
.Properties()
.Select(p => p.Name);
var allProperties = typeof(Resource)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => p.Name);
module.BindTo(myCurrentResourceInstance, allProperties.Except(definedProperties));
我在github上看了南希的源代码,我找不到任何暴露JSON属性列表的东西,它们的序列化器也是内部的。因此,您必须包含另一个库来进行解析(我使用Newtonsoft.Json)。
我希望你能以某种方式访问你的json来检索属性列表。由于我无法在INancyModule上找到它,但我猜您确实可以从更高的位置访问它。
我已经设法使我的部分更新工作使用Newtonsoft.Json。它不像我想要的那样干净,但至少它能工作。
var partialResourceAsJson = Request.Body.AsString();
JsonConvert.PopulateObject(partialResourceAsJson, myCurrentResourceInstance);