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

2024-02-02

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


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

public class Order
{
    [DisplayFormat(ConvertEmptyStringToNull=false)]
    public string Notes { get; set; }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐