【问题标题】:Web.Api deserialization fail for model parameter with different name具有不同名称的模型参数的 Web.Api 反序列化失败
【发布时间】:2013-06-10 12:12:18
【问题描述】:

我有一种方法,它将模型 [AccountLinkRequest] 作为带有 url 编码数据的参数。它默认使用 Json.NET,而且我不能使用设置 UseDataContractJsonSerializer = true 因为我有通用输出响应模型(在其他方法中)

[HttpPost]
public SomeResponse Link(AccountLinkRequest request)
{
    if (request.CustomerId == null)
        throw new Exception("Deserialization error here, pls help!");

    // other actions
}

这是我的模型类:

[DataContract]
[JsonObject]
public class AlertAccountLinkRequest
{
    [DataMember(Name = "id")]
    public string id { get; set; }

    [DataMember(Name = "customer_id")]
    [JsonProperty("customer_id")]
    public string CustomerId { get; set; }
}

问题: request.CustomerId 总是null。请求很简单:

web_service_URL/link?customer_id=customer_id&id=id(url 编码)

如果我使用 Customer_Id 而不是 CustomerId,一切都会好起来的,但我走上了绝路。谢谢!

【问题讨论】:

    标签: binding asp.net-web-api json.net datamember


    【解决方案1】:

    如何实现这一点并没有一个简单的答案。更多详情请阅读:

    How to bind to custom objects in action signatures in MVC/WebAPI

    总结:

    1. 在 Action 中手动调用解析函数
    2. 使用 TypeConverter 让复杂类型变得简单
    3. 使用自定义模型绑定器

    因此,例如,如果您创建能够使用某些属性的“SmartBinder”,您就可以获得您想要的。开箱即用,没有任何功能,只是命名约定......

    【讨论】:

    • Radim,谢谢您的回复。我仍然无法相信 DataMember / JsonProperty 没有为它服务。这与 ORM 一样,我们不能定义自己的属性名,而不是使用列名。顺便说一句,有 Json.NET 5.0+ 更新,但没有任何改变
    • 在这种情况下,我们谈论的是ModelBinder。我们想改变一个查询(查询字符串的一部分)以转换为一个对象。只有上述 3 种方法可用。你在说什么,是解析身体。为此,我们使用 MediaFormatters。这些可能非常强大,可调整,可扩展......所以有最大的不同。查询与正文。请求正文可以包含一个 JSON 可以使用一个 Json 属性(例如[JsonProperty(PropertyName='')])......在这种情况下不是。我知道的坏消息;(
    猜你喜欢
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2021-01-19
    • 1970-01-01
    • 2017-11-29
    • 2013-10-09
    相关资源
    最近更新 更多