attributes - .NET Core 模型在发布请求中与连字符属性名称绑定(bind)

标签 attributes asp.net-core http-post model-binding hyphenation

我已订阅 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"
}

使用以下代码片段,我可以将除“消息时间戳”之外的所有字段映射到我的 SmsReceipt。未填充任何消息时间戳字段。

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# 类中的属性匹配。

  2. 使用 JsonProperty(来自 Newtonsoft.Json)装饰您的 C# 类,您可以在其中指定应将发布数据中的哪些属性映射到此属性。

我还建议使用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; }
}

关于attributes - .NET Core 模型在发布请求中与连字符属性名称绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41410259/

相关文章:

javascript - 如何在 Zend Framework 中附加 js 文件时定义自定义属性?

c# - 您如何反射(reflection)应用于返回值的属性?

json - 如何使用 KQL extractjson 函数引用以 @ 符号开头的 XML 属性?

c# - 如何在ASP.NET Core中处理路由请求 "john.myexample.com"

c# - 为什么要为这个配置类创建一个接口(interface)呢?

c++ - '+' 替换为空格 Curl C++

javascript - .getAttribute ("name") 和 .name 有什么区别?

asp.net - 在 azure 上的 asp.net vnext 网站上禁用端口 80

android - 使用 android 复制来自 fiddler 的 HttpPost 请求

objective-c - Objective-C 中的 HTTP Post 请求不起作用