Reputation: 3257
I am using WebAPI to get the POST message. The body of the POST message:
{"datetime":"2017-01-06T20:40:44.2401244Z","filename":"somefilename.csv","datasourcename":"MyDataSource","error":"The uploaded file has no tags."}
The header included with the POST:
Content-type: application/json
My action method that handle the message: [HttpPost]
public void SaveMessage([FromBody] string msg)
{
MyModel w = JsonConvert.DeserializeObject<MyModel>(msg);
db.MyModels.Add(w);
db.SaveChanges();
}
My question is how do I encode the JSON so that I can parse it? I can't change the incoming message. What can I do in my method so that I can read it? Right now msg
always give me null
.
Upvotes: 0
Views: 703
Reputation: 247631
Given that you have no control over the data being sent, then as suggested in the comments, make sure you have a model that matches the desired object model of the JSON
public class MyModel {
public DateTime datetime { get; set; }
public string filename { get; set; }
public string datasourcename { get; set; }
public string error { get; set; }
}
And take advantage of the model binding capability of the Web API framework and let the action bind a strongly typed model from the body of the request.
[HttpPost]
public IHttpActionResult SaveMessage([FromBody] MyModel model) {
if(ModelState.IsValid) {
db.MyModels.Add(w);
if(db.SaveChanges() > 0)
return Ok();
}
return BadRequest();
}
If there are any issues with saving the message the action will return HTTP Status Code 400 Bad Request, otherwise it will return HTTP Status Code 200 OK.
Upvotes: 3