I'm new to C# and I'm trying to get the JSON response from a REST request using RestSharp;
The request I want to execute is the following one : "http://myurl.com/api/getCatalog?token=saga001"
. It works great if I'm executing it in a browser.
I've tried this :
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest("getCatalog?token=saga001");
var queryResult = client.Execute(request);
Console.WriteLine(queryResult);
And I get "RestSharp.RestReponse" instead of the JSON result I'm hopping for.
Thanks for your help !
var client = new RestClient("http://myurl.com/api/"); var request = new RestRequest("getCatalog? token=saga001"); var queryResult = client. Execute(request); Console. WriteLine(queryResult);
The main conclusion is that one is not better than the other, and we shouldn't compare them since RestSharp is a wrapper around HttpClient. The decision between using one of the two tools depends on the use case and the situation.
RestSharp supports sending XML or JSON body as part of the request. To add a body to the request, simply call AddJsonBody or AddXmlBody method of the IRestRequest instance. There is no need to set the Content-Type or add the DataFormat parameter to the request when using those methods, RestSharp will do it for you.
Try:
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest("getCatalog?token={token}", Method.GET);
request.AddParameter("token", "saga001", ParameterType.UrlSegment);
// request.AddUrlSegment("token", "saga001");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
Try as below:
var client = new RestClient("http://myurl.com/api/");
client.ClearHandlers();
var jsonDeserializer = new JsonDeserializer();
client.AddHandler("application/json", jsonDeserializer);
var request = new RestRequest("getCatalog?token=saga001");
var queryResult = client.Execute(request);
Console.WriteLine(queryResult);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With