我有一个简单的ApiController
public HttpResponseMessage Put(int orderid, [FromBody] Order order)
{
// Do something useful with order.Notes here
}
和一个类(实际的类包含更多属性)
public class Order
{
public string Notes { get; set; }
}
并希望处理以下类型的PUT请求
PUT http://localhost/api/orders/{orderid}
Content-Type: application/x-www-form-urlencoded
notes=sometext
一切正常,但空值传递为null
notes=blah // passes blah
notes= // Passes null
someothervalue=blah // Passes null
是否可以让ApiController区分空值和缺失值?
答案 0 :(得分:3)
您是否尝试使用DisplayFormatAttribute注释属性,例如
public class Order
{
[DisplayFormat(ConvertEmptyStringToNull=false)]
public string Notes { get; set; }
}
答案 1 :(得分:2)
此根来自调用ReplaceEmptyStringWithNull
而不是string.IsNullOrWhiteSpace
的{{1}}
要在整个WebAPI项目中修复此问题,您需要将string.IsNullOrEmpty
替换为将ModelMetadataProvider
设置为ConvertEmptyStringToNull
请参阅Set default for DisplayFormatAttribute.ConvertEmptyStringToNull to false
这实际上是在v6中“修复” - 请参阅https://github.com/aspnet/Mvc/issues/3593