我尝试实现ASP.NET MVC 5 WebAPI补丁。但是int值和枚举存在问题。 JSON反序列化“思考”哪个更好地将int转换为long,所以因为在我的int属性中我总是认为0 ...
所以我找到了“Microsoft.AspNet.JsonPatch.JsonPatchDocument”(还有很多其他人出版)
然后问题是,我在我的模型中总是无效
public async Task<IHttpActionResult> Patch( int id, [FromBody] Microsoft.AspNet.JsonPatch.JsonPatchDocument<Customer> model)
{
//model is allways == null
}
我正在使用POSTMAN将补丁发送为Body&gt; Raw中的json。标题是application / json。
我不明白为什么模型为null ...我需要在WebApiConfig上做任何事情?
我仍然尝试实现自定义JsonConverter,但问题是我有很多枚举类型,我需要为每个枚举创建一个?我试着这样做:
public class Int32EnumConverter<T> : JsonConverter
但问题出在WebApiConfig.cs中,你需要实现这个:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Int32EnumConverter<[I NEED HEAR Dynamic Enum Types>>);
有没有人帮助我?谢谢!
答案 0 :(得分:1)
实测值!我在Delta Patch上做了我的
public class JSONPatch<T>
{
private Dictionary<string, object> propsJson = new Dictionary<string, object>();
public JSONPatch()
{
Stream req = HttpContext.Current.Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
propsJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}
public JSONPatch(object model)
{
propsJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(model.ToString());
}
public void Patch(T model)
{
PropertyInfo[] properties = model.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
try
{
if (!propsJson.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
continue;
KeyValuePair<string, object> item = propsJson.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));
Type targetProp = model.GetType().GetProperty(property.Name).PropertyType;
Type targetNotNuable = Nullable.GetUnderlyingType(targetProp);
if (targetNotNuable != null)
{
targetProp = targetNotNuable;
}
if (item.Value.GetType() != typeof(Int64))
{
object newA = Convert.ChangeType(item.Value, targetProp);
model.GetType().GetProperty(property.Name).SetValue(model, newA, null);
}
else
{
int value = Convert.ToInt32(item.Value);
if (targetProp.IsEnum)
{
object newA = Enum.Parse(targetProp, value.ToString());
model.GetType().GetProperty(property.Name).SetValue(model, newA, null);
}
else
{
object newA = Convert.ChangeType(value, targetProp);
model.GetType().GetProperty(property.Name).SetValue(model, newA, null);
}
}
}
catch
{
}
}
}
}
现在:
public async Task<IHttpActionResult> Patch( int id, [FromBody]JSONPatch<Customer> model)
{
....
注意:未经过100%测试!空值失败。