RestSharp Post a JSON Object

JamesWillett picture JamesWillett · Aug 11, 2015 · Viewed 64.7k times · Source

I am trying to post the following JSON with RestSharp:

{"UserName":"UAT1206252627",
"SecurityQuestion":{
    "Id":"Q03",
    "Answer":"Business",
    "Hint":"The answer is Business"
},
}

I think that I am close, but I seem to be struggling with the SecurityQuestion (the API is throwing an error saying a parameter is missing, but it doesn't say which one)

This is the code I have so far:

var request = new RestRequest("api/register", Method.POST);
request.RequestFormat = DataFormat.Json;

request.AddParameter("UserName", "UAT1206252627");

SecurityQuestion securityQuestion = new SecurityQuestion("Q03");
request.AddParameter("SecurityQuestion", request.JsonSerializer.Serialize(securityQuestion));

IRestResponse response = client.Execute(request);

And my Security Question class looks like this:

public class SecurityQuestion
{
    public string id {get; set;}
    public string answer {get; set;}
    public string hint {get; set;}

    public SecurityQuestion(string id)
    {
         this.id = id;
         answer = "Business";
         hint = "The answer is Business";
    }
}

Can anyone tell me what I am doing wrong? Is there any other way to post the Security Question object ?

Many thanks.

Answer

Oluwafemi picture Oluwafemi · Aug 11, 2015

You need to specify the content-type in the header:

request.AddHeader("Content-type", "application/json");

Also AddParameter adds to POST or URL querystring based on Method

I think you need to add it to the body like this:

request.AddJsonBody(
    new 
    {
      UserName = "UAT1206252627", 
      SecurityQuestion = securityQuestion
    }); // AddJsonBody serializes the object automatically