28

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.

JamesWillett
  • 980
  • 2
  • 8
  • 20

5 Answers5

59

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
Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
  • 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? – JamesWillett Aug 11 '15 at 10:52
  • Can you give a sample method of the APl? – Oluwafemi Aug 11 '15 at 10:53
  • 4
    It does work for me: request.AddHeader("Content-Type", "application/json; charset=utf-8"); request.AddJsonBody(yourobject); – Andrei Drynov Mar 08 '16 at 19:12
  • 1
    Thank you for your solution – Thomas.Benz Aug 30 '17 at 17:25
  • 1
    Really doesn't work. Correct approach is: `r.AddParameter("application/json", JsonSerializerHelper.Serialize(keys), ParameterType.RequestBody);` – lyolikaa Dec 07 '18 at 09:09
  • I am passing an array and gets a response `"StatusCode: NotFound, Content-Type: , Content-Length: 0)"` here's what I did: request.AddHeader("Content-type", "application/json"); request.AddJsonBody(branchCode); – ThEpRoGrAmMiNgNoOb Jun 24 '19 at 06:59
  • Don't forget to use @ with reserved words, for example `request.AddJsonBody(new { @event = "view" });` – Konstantin Nov 05 '19 at 15:15
27

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 !

JamesWillett
  • 980
  • 2
  • 8
  • 20
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);
Eternal21
  • 4,190
  • 2
  • 48
  • 63
  • 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 '18 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;
    }
FunkySax
  • 51
  • 1
  • 2
2

RestSharp supported from object by AddObject method

request.AddObject(securityQuestion);
Amir Astaneh
  • 2,152
  • 1
  • 20
  • 20