Difference between RestSharp methods AddParameter and AddQueryParameter using HttpGET

前端 未结 2 739
抹茶落季
抹茶落季 2021-02-18 17:55

I\'m using RestSharp to call an external API.

This works:

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

foreach         


        
相关标签:
2条回答
  • 2021-02-18 18:27

    To answer the OP and anyone else who might have trouble with the concept. It took me awhile to get around to the concept. You probably need to visualise the RESTful standard of how to construct a GET request message in a url against constructing for a POST request message.

    You will notice that for GET , the parameter(s) are attached to the URL header whereas for the POST , the parameter(s) are placed in the body of the message. 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" . For the POST , the parameters contact_name and company_name are located in the bottom of the message body.

    Eg:

    GET message format :

    GET http://www.consumerdiarydemo.cbrnetwork.test.au/api/ConsumerDiary/getSizesOrFlavours/Flavours HTTP/1.1 Host: www.consumerdiarydemo.cbrnetwork.test.au Connection: keep-alive Accept: application/json User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Referer: http://www.consumerdiarydemo.cbrnetwork.test.au/ConsumerDiaryPage2template Accept-Encoding: gzip, deflate, sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6


    POST message format :

    POST http://localhost:1234567/api/customers HTTP/1.1 Accept: application/json, text/javascript, /; q=0.01 X-Requested-With: XMLHttpRequest Content-Type: application/x-www-form-urlencoded; charset=UTF-8

    {"contact_name":"value_data1","company_name":"value_data2"}

    0 讨论(0)
  • 2021-02-18 18:32

    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.

    0 讨论(0)
提交回复
热议问题