Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between RestSharp methods AddParameter and AddQueryParameter using HttpGET

Tags:

I'm using RestSharp to call an external API.

This works:

var client = new RestClient(apiUrl);
var request = new RestRequest(myurl, Method.GET);

foreach (var param in parameters)
{
    request.AddQueryParameter(param.Key, param.Value);
}
var response = client.Execute(request);

This doesn't:

var client = new RestClient(apiUrl);
var request = new RestRequest(myurl, Method.GET);

foreach (var param in parameters)
{
    request.AddParameter(param.Key, param.Value);
}
var response = client.Execute(request);

Resulting in:

System.Exception: API Call MyWebAPIMethod GET: Failed with status code 0 - Unable to connect to the remote server

What's the difference between AddParameter and AddQueryParameter?

According to the documentation they should function the same when using HttpGET and according to Fiddler they seem to generate the same URL as well.

like image 301
Nic Avatar asked Sep 18 '15 02:09

Nic


People also ask

What is the purpose of AddParameter method of RestRequest class?

RestSharp 's method AddQueryParameter() will only add the (Query) parameters in the header of the message, whereas the AddParameter() will only add the parameters to the mesasge body. As demonstrated below the GET has one query parameter with a value of "Flavours" .

What is RestSharp used for?

RestSharp is a C# library used to build and send API requests, and interpret the responses. It is used as part of the C#Bot API testing framework to build the requests, send them to the server, and interpret the responses so assertions can be made.

Does RestSharp use HttpClient?

Since RestSharp uses the HttpClient, we should consider similar issues regarding the RestClient instantiation.

How do I add a query parameter to RestSharp?

var client = new RestClient("http://localhost"); var request = new RestRequest("resource", Method. POST); request. AddParameter("auth_token", "1234"); request.


1 Answers

To answer your question

AddQueryParameter adds a parameter in the query string as ParameterType.QueryString whereas AddParameter(string, object) adds the parameter as ParameterType.GetOrPost

For more details on each parameter type, see:

GetOrPost: https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest#getorpost

QueryString: https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest#querystring

To solve your problem

It seems it is unrelated to the type of parameter, because the exception thrown seems to indicate you aren't even connecting to the remote server.

make sure you pass the same apiUrl / myUrl in both cases.

like image 82
Fabio Salvalai Avatar answered Sep 20 '22 19:09

Fabio Salvalai