ASP.NET WebAPI passing empty string in urlencoded body as null

I have a simple ApiController

public HttpResponseMessage Put(int orderid, [FromBody] Order order)
{
    // Do something useful with order.Notes here
}

and a class (the actual class contains several more properties)

public class Order
{
    public string Notes { get; set; }
}

and wish to handle PUT requests of the following type

PUT http://localhost/api/orders/{orderid}
Content-Type: application/x-www-form-urlencoded

notes=sometext

Everything works fine, but empty values are passed as null

notes=blah            // passes blah
notes=                // Passes null
someothervalue=blah   // Passes null

Is it possible to have ApiController distinguish between empty values and missing values?


您是否尝试使用DisplayFormatAttribute注释该属性,

public class Order
{
    [DisplayFormat(ConvertEmptyStringToNull=false)]
    public string Notes { get; set; }
}

The root of this comes from the ReplaceEmptyStringWithNull that calls string.IsNullOrWhiteSpace instead of string.IsNullOrEmpty

To fix this across your entire WebAPI project, you need to swap out the ModelMetadataProvider with one that sets the ConvertEmptyStringToNull to false

See Set default for DisplayFormatAttribute.ConvertEmptyStringToNull to false

This was actually "fixed" in v6 - see https://github.com/aspnet/Mvc/issues/3593

链接地址: http://www.djcxy.com/p/68904.html

上一篇: 单一登录2个子域名,一个Java,一个.NET

下一篇: ASP.NET WebAPI将urlencoded body中的空字符串传递为null