.NET 核心模型在 post 请求中与带连字符的属性名称绑定

.NET core model binding with hyphenated attribute names in post request

我订阅了 Nexmo SMS 服务,他们为入站 SMS 提供回调 URL。 post 请求在通知收到短信时给出以下 Json 结构:

{
  "msisdn": "441632960960",
  "to": "441632960961",
  "messageId": "02000000E68951D8",
  "text": "Hello7",
  "type": "text",
  "keyword": "HELLO7",
  "message-timestamp": "2016-07-05 21:46:15"
}

使用以下代码片段,我可以将除 'message-timestamp' 之外的所有字段映射到我的 SmsReceipt。 None 的消息时间戳字段已填充。

public class SmsReceipt
{

    public string msisdn { get; set; }
    public string to { get; set; }
    public string messageId { get; set; }
    public string text { get; set; }
    public string type { get; set; }
    public string keyword { get; set; }
    public string messagetimestamp { get; set; }
    public string messageTimestamp { get; set; }
    public string message_timestamp { get; set; }
}

[HttpPost("inboundsms")]
public async Task<IActionResult> Post([FromBody] SmsReceipt receipt)
{
    return StatusCode(200);
}

我想这同样适用于带有其他特殊字符(例如“.”)的传入请求。非常感谢任何想法。

您的 属性 姓名应与发送数据中的 属性 姓名相匹配。看起来您的负载 属性 名称是 message-timestamp。您不能创建其中包含 - 的 C# 属性。所以你的选择是

  1. 要么更新您的 json 有效负载 属性 以匹配来自您的 C# class.

  2. JsonProperty(From Newtonsoft.Json) 装饰您的 C# class,您可以在其中指定已发布数据中的 属性 应映射到此属性.

我还建议使用 DateTime 类型。该类型是为处理日期时间值而创建的。

public class SmsReceipt
{
    public string Msisdn { get; set; }
    public string To { get; set; }
    public string MessageId { get; set; }
    public string Text { get; set; }
    public string Type { get; set; }
    public string Keyword { get; set; }

    [JsonProperty("message-timestamp")]
    public DateTime Messagetimestamp { get; set; }
}