user3562286
user3562286

Reputation: 159

Converting Curl to C# with RestSharp

I'm trying to convert this curl command to C# using RestSharp, and I'm having problems specifically with the data parameter (token and uri variables have been replaced w/dummy values for this example):

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'UserToken: usertoken' --header 'AppToken: apptoken' -d '[{"individualRecordNumber":"foo","score":"bar"}]' 'apiEndpoint'

I've been able to successfully do several GET requests within this same API, so I'm good with the overall request format and headers, I'm just having issues figuring out how to format the data and where to append it. Here's the rest of the request without the data:

var client = new RestClient(apiEndpoint);
var request = new RestRequest(Method.POST);
request.AddHeader("usertoken", usertoken);
request.AddHeader("apptoken", apptoken);
request.AddHeader("content-type", "application/json");
    
IRestResponse response = client.Execute(request);

I've tried using both AddParameter and AddJsonBody with various combinations of serialized and unserialized versions of the data.

Example of building data directly as string:

string examInfo = @"[{""individualRecordNumber"":""foo"",""score"":""bar""}]";

Example of building data as object:

object[] arrayObj = new object[1];
arrayObj[0] = new { individualRecordNumber = "foo", score = "bar" };

This is for a project with an extremely tight turnaround, so any help is much appreciated!

Upvotes: 1

Views: 2564

Answers (1)

granadaCoder
granadaCoder

Reputation: 27852

If you need a Post, to "wire in" the Post-Body, AddParameter has this overload

request.AddParameter("application/json", "mybody", ParameterType.RequestBody);

or , in your case

request.AddParameter("application/json", examInfo, ParameterType.RequestBody);

but maybe better (if you have later version)

request.AddJsonBody(new { A = "foo", B = "bar" });

And the initial constructor: (which you seem to have, but making sure to note it for future readers)

var request = new RestRequest(Method.POST);

More full example:

var client = new RestClient("https:blahblahblah");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");

/* option1 */
request.AddParameter("application/json", "{mybody:'yes'}", ParameterType.RequestBody);

/* OR option 2 */
request.AddJsonBody(new { A = "foo", B = "bar" });

IRestResponse response = client.Execute(request);

Upvotes: 3

Related Questions