尝试利用System.Web.Http.OData.Delta http://blogs.msdn.com/b/alexj/archive/2012/08/15/odata-support-in-asp-net-web-api.aspx实施PATCH https://www.rfc-editor.org/rfc/rfc5789ASP.NET Web API 服务中的方法,但似乎无法将更改应用于类型的属性IEnumerable<T>
。我正在使用 Delta 的最新 Git 版本 (2012.2-rc-76-g8a73abe)。有人能够做到这一点吗?
考虑这种数据类型,应该可以在对 Web API 服务的 PATCH 请求中更新该数据类型:
public class Person
{
HashSet<int> _friends = new HashSet<int>();
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public IEnumerable<int> Friends
{
get { return _friends; }
set
{
_friends = value != null ? new HashSet<int>(value) : new HashSet<int>();
}
}
public Person(int id, string firstName, string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
public Person()
{
}
}
此 Web API 方法通过以下方式实现对 Person 的修补Delta<Person>
:
public void Patch(int id, Delta<Person> delta)
{
var person = _persons.Single(p => p.Id == id);
delta.Patch(person);
}
如果我向服务发送包含以下 JSON 的 PATCH 请求,则该人的Friends
属性应该更新,但遗憾的是它没有发生:
{"Friends": [1]}
问题的关键其实是如何让Delta更新Friends
有了这个数据。另请参阅CodePlex 上的讨论 http://aspnetwebstack.codeplex.com/discussions/429382.
问题可能是 Deta 会尝试分配 JSONJArray
给你的Hashset<int>
如果您将它用于 JsonMEdiaTypeFormatter 并且您内部化了 Delta 代码(意味着您可以修改它),您必须执行类似的操作(这很粗糙,但有效):
里面,bool TrySetPropertyValue(string name, object value)
of Delta<T>
,它返回 false:
if (value != null && !cacheHit.Property.PropertyType.IsPrimitive && !isGuid && !cacheHit.Property.PropertyType.IsAssignableFrom(value.GetType()))
{
return false;
}
改成:
var valueType = value.GetType();
var propertyType = cacheHit.Property.PropertyType;
if (value != null && !propertyType.IsPrimitive && !propertyType.IsAssignableFrom(valueType))
{
var array = value as JArray;
if (array == null)
return false;
var underlyingType = propertyType.GetGenericArguments().FirstOrDefault() ??
propertyType.GetElementType();
if (underlyingType == typeof(string))
{
var a = array.ToObject<IEnumerable<string>>();
value = Activator.CreateInstance(propertyType, a);
}
else if (underlyingType == typeof(int))
{
var a = array.ToObject<IEnumerable<int>>();
value = Activator.CreateInstance(propertyType, a);
}
else
return false;
}
这仅适用于集合int
or string
但希望能把你推向一个好的方向。
例如,现在您的模型可以具有:
public class Team {
public HashSet<string> PlayerIds { get; set; }
public List<int> CoachIds { get; set; }
}
并且您将能够成功更新它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)