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

1.7k views Asked by At

I've subscribed to the Nexmo SMS service and they offer a callback URL for inbound SMS. The post request gives the following Json structure when notifying of SMS receipt:

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

Using the following code snippet, I can map all of the fields to my SmsReceipt apart from 'message-timestamp'. None of the message timestamp fields are populated.

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);
}

I guess the same applies to incoming requests with other special characters such as '.' Any ideas greatly appreciated.

1

There are 1 answers

1
Shyju On BEST ANSWER

Your property name should match with the property name in the data being sent. Looks like your payload property name is message-timestamp. You cannot create a C# property with a - in it. So your options are

  1. Either update your json payload property to match with one from your C# class.

  2. Decorate your C# class with JsonProperty(From Newtonsoft.Json) where you specify what property from the posted data should be mapped to this property.

Also i suggest use the DateTime type. That type was created to deal with date time value.

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; }
}