29

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.

5 Answers 5

60

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
7
  • Thanks for your answer Oluwafemi, but I am still getting the same error (that a parameter is missing) - I know it seems like this should work, but is there anything else I can try? Aug 11, 2015 at 10:52
  • Can you give a sample method of the APl?
    – Oluwafemi
    Aug 11, 2015 at 10:53
  • 4
    It does work for me: request.AddHeader("Content-Type", "application/json; charset=utf-8"); request.AddJsonBody(yourobject); Mar 8, 2016 at 19:12
  • 1
    Thank you for your solution Aug 30, 2017 at 17:25
  • 1
    Really doesn't work. Correct approach is: r.AddParameter("application/json", JsonSerializerHelper.Serialize(keys), ParameterType.RequestBody);
    – lyolikaa
    Dec 7, 2018 at 9:09
28

Thanks again for your help. To get this working I had to submit everything as a single parameter. This is the code I used in the end.

First I made a couple of classes called Request Object and Security Question:

public class SecurityQuestion
{
    public string Id { get; set; }
    public string Answer { get; set; }
    public string Hint { get; set; }
}

public class RequestObject
{
    public string UserName { get; set; }
    public SecurityQuestion SecurityQuestion { get; set; }
}

Then I just added it as a single parameter, and serialized it to JSON before posting it, like so:

var yourobject = new RequestObject
            {
                UserName = "UAT1206252627",
                SecurityQuestion = new SecurityQuestion
                {
                    Id = "Q03",
                    Answer = "Business",
                    Hint = "The answer is Business"
                },
            };
var json = request.JsonSerializer.Serialize(yourobject);

request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);

IRestResponse response = client.Execute(request);

and it worked !

0
11

To post raw json body string, AddBody(), or AddJsonBody() methods will not work. Use the following instead

request.AddParameter(
   "application/json",
   "{ \"username\": \"johndoe\", \"password\": \"secretpassword\" }", // <- your JSON string
   ParameterType.RequestBody);
1
  • 1
    Yes, the raw approach is many times useful, for example, when passing in a body that is stored in a database
    – BigMan73
    Oct 10, 2018 at 19:52
5

It looks like the easiest way to do this is to let RestSharp handle all of the serialization. You just need to specify the RequestFormat like so. Here's what I came up with for what I'm working on. .

    public List<YourReturnType> Get(RestRequest request)
    {
        var request = new RestRequest
        {
            Resource = "YourResource",
            RequestFormat = DataFormat.Json,
            Method = Method.POST
        };
        request.AddBody(new YourRequestType());

        var response = Execute<List<YourReturnType>>(request);
        return response.Data;
    }

    public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient(_baseUrl);

        var response = client.Execute<T>(request);
        return response.Data;
    }
2

RestSharp supported from object by AddObject method

request.AddObject(securityQuestion);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.