0

I am developing a API using OWINHost and in my controller i've got an post method that is expecting a Json. If the Json is structured properly, everything is working just fine, but i am not being able to throw an error if the structure is different.

I thougth about instead of receive a type "SMS" as an parameter, receives a string then use Newtonsoft.Json to parse that string, if it parses incorrectly throw the error, but i am not sure if this is good pracctice.

    [HttpPost]
    public HttpResponseMessage NewMessage(HttpRequestMessage request, [FromBody] SMS sms)
    {
        // some code

        //return Ok if everything runs smoothly
        return request.CreateResponse(HttpStatusCode.OK);
    }

I need to know when the structure of the json is incorrect so i can throw an error status.

{
  "Number": "12345",
  "Content": "Test"
}

This is the json structure, and this is my SMS class

public class SMS
{
    public string Number{ get; set; }

    public string Content{ get; set; }
}
  • Of course it is ok to wrap your parsing of the received message in a `try-catch` block.You should prepare for the worst when developing an `API` and one of the first things that can crash is a ill formed request.So you have to treat bad requests as well. – Bercovici Adrian May 23 '19 at 18:14
  • 2
    This is what model validation is for. An invalid model should result in a 400 BAD REQUEST. –  May 23 '19 at 18:15
  • As @Amy said, use model validation: look at this question, https://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api. You can mark the attributes of your model as `Required` and handle the errors either in the controller or using an action filter as described in the answers. – colinD May 23 '19 at 18:44

0 Answers0