ASP.NET WebAPI将urlencoded正文中的空字符串作为null传递

时间:2013-01-25 12:21:46

标签: asp.net .net web-services asp.net-web-api urlencode

我有一个简单的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区分空值和缺失值?

2 个答案:

答案 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