Reputation: 1246
I have a method that receives some data from a 3rd party. The data is a JSON object (not a string, I tried receiving as a string and data was not accessable - the data property was null)
[HttpPost]
[Route("com/sendemail")]
public async Task<IActionResult> SendEmail(dynamic data)
{
mailData = JsonConvert.DeserializeObject<EmailTemplate>(data);
}
I am trying to get it into a .net object which is needed to be passed into another function I dont control. It has to be an EmailTemplate object, which is defined as:
public class EmailTemplate
{
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string EmailHtml { get; set; }
}
mailData is of type EmailTemplate. The Deserialize object call fails because that method requires a string, which this isnt. Ive tried other methods, such as
mailData = (EmailTemplate)data;
and
mailData.To = data.To
but neither work. Any pointers gratefully received.
PS. Heres what the data looks like in visual studio
Upvotes: 0
Views: 267
Reputation: 331
When your class matches the Json-object that is sent, this will work:
public async Task<IActionResult> SendEmail([FromBody]EmailTemplate data)
When you use your dynamic approach, you need to access the dynamic objects members and create your .NET object with them.
public async Task<IActionResult> SendEmail([FromBody]dynamic data)
{
mailData = new EmailTemplate {
From = data.From,
To = data.To,
Subject = data.Subject,
EmailHtml = data.EmailHtml
};
}
Upvotes: 2
Reputation: 1529
Your controller couldn't accept a string, because (I assume) the request's content-type is 'application/json' and the framework couldn't convert it to a string. You should change your controller's data
parameter type to EmailTemplate
:
[HttpPost]
[Route("com/sendemail")]
public async Task<IActionResult> SendEmail([FromBody] EmailTemplate data)
{
//...
}
Upvotes: 2