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

不羁的心 提交于 2019-12-08 18:58:38

问题


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?


回答1:


Have you tried annotating the property with DisplayFormatAttribute, like,

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



回答2:


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



来源:https://stackoverflow.com/questions/14521741/asp-net-webapi-passing-empty-string-in-urlencoded-body-as-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!