为什么 Delta.Patch 不将字节数组更新为空值?
Why won't Delta.Patch update a byte array to a null value?
我的对象模型有一个用于存储图像的字节数组。当我尝试通过 Delta.Patch 将此字节数组更新为新值时,它工作得很好,但是当我尝试将其更新为 null 时,它失败了。
这是我正在查看的代码行是
update.Patch(entity);
如果我查看 update
对象,我可以看到 update.ChangedProperties
包含我的图像 属性,因此它知道应该更新它。我还可以看到 update._instance
包含图像字段具有空值的对象实例,我可以使用 Fiddler 查看更改后的值作为空值发送。
但是当我在调用 .Patch
后查看 entity
对象时,当新值应该为 null 时,字节数组没有更新。 Delta 中的其他更新得到正确更新,但不是这个字节数组。
这可能是什么原因造成的?我还是 OData 的新手,不确定我是否遗漏了一些明显的东西。
我查看了 OData(WebAPI version) 的源代码并(可能)发现了核心问题。问题也适用于 ASP.NET 核心版本,因为它与 ASP.NET WebAPI 共享代码库。
问题
你调用了 Patch(TStructuralType original)
方法,它又调用了 CopyChangedValues(TStructuralType original)
方法。两人都是 Delta<T>
class
的 public 成员
public void Patch(TStructuralType original)
{
CopyChangedValues(original);
}
内部 CopyChangedValues(TStructuralType original)
方法是一段代码,用于处理将值复制到原始实例。代码遍历 PropertyAccessor<TStructuralType>
数组并调用 Copy(TStructuralType from, TStructuralType to)
方法。
// For regular non-structural properties at current level.
PropertyAccessor<TStructuralType>[] propertiesToCopy =
this._changedProperties.Select(s => _allProperties[s]).ToArray();
foreach (PropertyAccessor<TStructuralType> propertyToCopy in propertiesToCopy)
{
propertyToCopy.Copy(_instance, original);
}
在 PropertyAccessor<TStructuralType>
中实现的 Copy(TStructuralType from, TStructuralType to)
中,您会发现对抽象 SetValue(TStructuralType instance, object value)
.
的调用
public void Copy(TStructuralType from, TStructuralType to)
{
if (from == null)
{
throw Error.ArgumentNull("from");
}
if (to == null)
{
throw Error.ArgumentNull("to");
}
SetValue(to, GetValue(from));
}
此方法由FastPropertyAccessor<TStructuralType>
class实现。
public override void SetValue(TStructuralType instance, object value)
{
if (instance == null)
{
throw Error.ArgumentNull("instance");
}
if (_isCollection)
{
DeserializationHelpers.SetCollectionProperty(instance, _property.Name, edmPropertyType: null,
value: value, clearCollection: true);
}
else
{
_setter(instance, value);
}
}
重要的代码行是 if (_isCollection)
。此布尔标志在构造函数中设置,并在 TypeHelper
class.
中调用 IsCollection()
静态方法
public FastPropertyAccessor(PropertyInfo property)
: base(property)
{
_property = property;
_isCollection = TypeHelper.IsCollection(property.PropertyType);
if (!_isCollection)
{
_setter = PropertyHelper.MakeFastPropertySetter<TStructuralType>(property);
}
_getter = PropertyHelper.MakeFastPropertyGetter(property);
}
在IsCollection(Type clrType)
中我们遍历对IsCollection(this Type type, out Type elementType)
的调用。
public static bool IsCollection(Type clrType)
{
Type elementType;
return TypeHelper.IsCollection(clrType, out elementType);
}
这里是 // see if this type should be ignored.
评论之后的重要几行(这很奇怪,可能表明有人忘记完成他已经开始的事情),其中只有 string
(char[]
) 被排除在外。其他数组(包括 byte[]
)跳至以下代码,这些代码积极评估 byte[](和任何其他数组类型),因为这些类型正在实现 IEnumerable<T>
接口。
public static bool IsCollection(Type clrType, out Type elementType)
{
if (clrType == null)
{
throw Error.ArgumentNull("clrType");
}
elementType = clrType;
// see if this type should be ignored.
if (clrType == typeof(string))
{
return false;
}
Type collectionInterface
= clrType.GetInterfaces()
.Union(new[] { clrType })
.FirstOrDefault(
t => TypeHelper.IsGenericType(t)
&& t.GetGenericTypeDefinition() == typeof(IEnumerable<>));
if (collectionInterface != null)
{
elementType = collectionInterface.GetGenericArguments().Single();
return true;
}
return false;
}
如果我们跳回 SetValue(TEntityType entity, object value)
方法实现,我们最终会在 DeserializationHelpers
class.
中调用 DeserializationHelpers.SetCollectionProperty(entity, _property.Name, edmPropertyType: null, value: value, clearCollection: true);
if (_isCollection)
{
DeserializationHelpers.SetCollectionProperty(instance, _property.Name, edmPropertyType: null,
value: value, clearCollection: true);
}
很明显,此方法的实现具有很强的防御性,可以避免在集合值为 null
的情况下抛出异常。该方法的第一行是 if (value != null)
并且没有 else
块或要执行的代码块之后的代码。我们可以从字面上说,对于每个实现 IEnumerable<T>
的类型都会忽略空值,因此不会设置。
internal static void SetCollectionProperty(object resource, string propertyName,
IEdmCollectionTypeReference edmPropertyType, object value, bool clearCollection)
{
if (value != null)
{
IEnumerable collection = value as IEnumerable;
Contract.Assert(collection != null,
"SetCollectionProperty is always passed the result of ODataFeedDeserializer or ODataCollectionDeserializer");
Type resourceType = resource.GetType();
Type propertyType = GetPropertyType(resource, propertyName);
Type elementType;
if (!TypeHelper.IsCollection(propertyType, out elementType))
{
string message = Error.Format(SRResources.PropertyIsNotCollection, propertyType.FullName, propertyName, resourceType.FullName);
throw new SerializationException(message);
}
IEnumerable newCollection;
if (CanSetProperty(resource, propertyName) &&
CollectionDeserializationHelpers.TryCreateInstance(propertyType, edmPropertyType, elementType, out newCollection))
{
// settable collections
collection.AddToCollection(newCollection, elementType, resourceType, propertyName, propertyType);
if (propertyType.IsArray)
{
newCollection = CollectionDeserializationHelpers.ToArray(newCollection, elementType);
}
SetProperty(resource, propertyName, newCollection);
}
else
{
// get-only collections.
newCollection = GetProperty(resource, propertyName) as IEnumerable;
if (newCollection == null)
{
string message = Error.Format(SRResources.CannotAddToNullCollection, propertyName, resourceType.FullName);
throw new SerializationException(message);
}
if (clearCollection)
{
newCollection.Clear(propertyName, resourceType);
}
collection.AddToCollection(newCollection, elementType, resourceType, propertyName, propertyType);
}
}
}
解决方案 1
第一个可能的解决方案是创建自定义模型绑定器并处理 byte[]
的 null
值,返回空字节数组并将 NullByteArrayModelBinder
class 添加到模型绑定器。
免责声明:未测试,但应该可以。
public class NullByteArrayModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if(bindingContext.ModelType == typeof(byte[])) {
return base.BindModel(controllerContext, bindingContext) ?? new byte[0];
}
return base.BindModel(controllerContext, bindingContext);
}
}
这种方法有一个缺点。 OData 的消费者还需要在现在进行 array != null
检查的任何地方处理空数组 array.Length > 0
。
解决方案 2
第二个选项是自定义序列化和反序列化。
序列化:从空 array
到 null
=> array.Length > 0 ? array : null;
反序列化:从 null
到空 array
=> array ?? new byte[0];
希望对您有所帮助!
我的对象模型有一个用于存储图像的字节数组。当我尝试通过 Delta.Patch 将此字节数组更新为新值时,它工作得很好,但是当我尝试将其更新为 null 时,它失败了。
这是我正在查看的代码行是
update.Patch(entity);
如果我查看 update
对象,我可以看到 update.ChangedProperties
包含我的图像 属性,因此它知道应该更新它。我还可以看到 update._instance
包含图像字段具有空值的对象实例,我可以使用 Fiddler 查看更改后的值作为空值发送。
但是当我在调用 .Patch
后查看 entity
对象时,当新值应该为 null 时,字节数组没有更新。 Delta 中的其他更新得到正确更新,但不是这个字节数组。
这可能是什么原因造成的?我还是 OData 的新手,不确定我是否遗漏了一些明显的东西。
我查看了 OData(WebAPI version) 的源代码并(可能)发现了核心问题。问题也适用于 ASP.NET 核心版本,因为它与 ASP.NET WebAPI 共享代码库。
问题
你调用了 Patch(TStructuralType original)
方法,它又调用了 CopyChangedValues(TStructuralType original)
方法。两人都是 Delta<T>
class
public void Patch(TStructuralType original)
{
CopyChangedValues(original);
}
内部 CopyChangedValues(TStructuralType original)
方法是一段代码,用于处理将值复制到原始实例。代码遍历 PropertyAccessor<TStructuralType>
数组并调用 Copy(TStructuralType from, TStructuralType to)
方法。
// For regular non-structural properties at current level.
PropertyAccessor<TStructuralType>[] propertiesToCopy =
this._changedProperties.Select(s => _allProperties[s]).ToArray();
foreach (PropertyAccessor<TStructuralType> propertyToCopy in propertiesToCopy)
{
propertyToCopy.Copy(_instance, original);
}
在 PropertyAccessor<TStructuralType>
中实现的 Copy(TStructuralType from, TStructuralType to)
中,您会发现对抽象 SetValue(TStructuralType instance, object value)
.
public void Copy(TStructuralType from, TStructuralType to)
{
if (from == null)
{
throw Error.ArgumentNull("from");
}
if (to == null)
{
throw Error.ArgumentNull("to");
}
SetValue(to, GetValue(from));
}
此方法由FastPropertyAccessor<TStructuralType>
class实现。
public override void SetValue(TStructuralType instance, object value)
{
if (instance == null)
{
throw Error.ArgumentNull("instance");
}
if (_isCollection)
{
DeserializationHelpers.SetCollectionProperty(instance, _property.Name, edmPropertyType: null,
value: value, clearCollection: true);
}
else
{
_setter(instance, value);
}
}
重要的代码行是 if (_isCollection)
。此布尔标志在构造函数中设置,并在 TypeHelper
class.
IsCollection()
静态方法
public FastPropertyAccessor(PropertyInfo property)
: base(property)
{
_property = property;
_isCollection = TypeHelper.IsCollection(property.PropertyType);
if (!_isCollection)
{
_setter = PropertyHelper.MakeFastPropertySetter<TStructuralType>(property);
}
_getter = PropertyHelper.MakeFastPropertyGetter(property);
}
在IsCollection(Type clrType)
中我们遍历对IsCollection(this Type type, out Type elementType)
的调用。
public static bool IsCollection(Type clrType)
{
Type elementType;
return TypeHelper.IsCollection(clrType, out elementType);
}
这里是 // see if this type should be ignored.
评论之后的重要几行(这很奇怪,可能表明有人忘记完成他已经开始的事情),其中只有 string
(char[]
) 被排除在外。其他数组(包括 byte[]
)跳至以下代码,这些代码积极评估 byte[](和任何其他数组类型),因为这些类型正在实现 IEnumerable<T>
接口。
public static bool IsCollection(Type clrType, out Type elementType)
{
if (clrType == null)
{
throw Error.ArgumentNull("clrType");
}
elementType = clrType;
// see if this type should be ignored.
if (clrType == typeof(string))
{
return false;
}
Type collectionInterface
= clrType.GetInterfaces()
.Union(new[] { clrType })
.FirstOrDefault(
t => TypeHelper.IsGenericType(t)
&& t.GetGenericTypeDefinition() == typeof(IEnumerable<>));
if (collectionInterface != null)
{
elementType = collectionInterface.GetGenericArguments().Single();
return true;
}
return false;
}
如果我们跳回 SetValue(TEntityType entity, object value)
方法实现,我们最终会在 DeserializationHelpers
class.
DeserializationHelpers.SetCollectionProperty(entity, _property.Name, edmPropertyType: null, value: value, clearCollection: true);
if (_isCollection)
{
DeserializationHelpers.SetCollectionProperty(instance, _property.Name, edmPropertyType: null,
value: value, clearCollection: true);
}
很明显,此方法的实现具有很强的防御性,可以避免在集合值为 null
的情况下抛出异常。该方法的第一行是 if (value != null)
并且没有 else
块或要执行的代码块之后的代码。我们可以从字面上说,对于每个实现 IEnumerable<T>
的类型都会忽略空值,因此不会设置。
internal static void SetCollectionProperty(object resource, string propertyName,
IEdmCollectionTypeReference edmPropertyType, object value, bool clearCollection)
{
if (value != null)
{
IEnumerable collection = value as IEnumerable;
Contract.Assert(collection != null,
"SetCollectionProperty is always passed the result of ODataFeedDeserializer or ODataCollectionDeserializer");
Type resourceType = resource.GetType();
Type propertyType = GetPropertyType(resource, propertyName);
Type elementType;
if (!TypeHelper.IsCollection(propertyType, out elementType))
{
string message = Error.Format(SRResources.PropertyIsNotCollection, propertyType.FullName, propertyName, resourceType.FullName);
throw new SerializationException(message);
}
IEnumerable newCollection;
if (CanSetProperty(resource, propertyName) &&
CollectionDeserializationHelpers.TryCreateInstance(propertyType, edmPropertyType, elementType, out newCollection))
{
// settable collections
collection.AddToCollection(newCollection, elementType, resourceType, propertyName, propertyType);
if (propertyType.IsArray)
{
newCollection = CollectionDeserializationHelpers.ToArray(newCollection, elementType);
}
SetProperty(resource, propertyName, newCollection);
}
else
{
// get-only collections.
newCollection = GetProperty(resource, propertyName) as IEnumerable;
if (newCollection == null)
{
string message = Error.Format(SRResources.CannotAddToNullCollection, propertyName, resourceType.FullName);
throw new SerializationException(message);
}
if (clearCollection)
{
newCollection.Clear(propertyName, resourceType);
}
collection.AddToCollection(newCollection, elementType, resourceType, propertyName, propertyType);
}
}
}
解决方案 1
第一个可能的解决方案是创建自定义模型绑定器并处理 byte[]
的 null
值,返回空字节数组并将 NullByteArrayModelBinder
class 添加到模型绑定器。
免责声明:未测试,但应该可以。
public class NullByteArrayModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if(bindingContext.ModelType == typeof(byte[])) {
return base.BindModel(controllerContext, bindingContext) ?? new byte[0];
}
return base.BindModel(controllerContext, bindingContext);
}
}
这种方法有一个缺点。 OData 的消费者还需要在现在进行 array != null
检查的任何地方处理空数组 array.Length > 0
。
解决方案 2
第二个选项是自定义序列化和反序列化。
序列化:从空 array
到 null
=> array.Length > 0 ? array : null;
反序列化:从 null
到空 array
=> array ?? new byte[0];
希望对您有所帮助!