Search code examples
c#console-application

How to call Web API in Console Application using Query string Param


I have parameter's In my Query string so I need to pass like below given URL:

URL + ?dd={{Some Json Data}}&accessKey=ddfr54r5g5r

WebClient webClient = new WebClient();
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
string url = "URL + ?dd={{Some Json Data}}&accessKey=ddfr54r5g5r";
var jsonData = webClient.DownloadData(url);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
RootObject obj = new RootObject();
obj = (RootObject)ser.ReadObject(new MemoryStream(jsonData));

Can anyone share some method which will be working for your API.


Solution

  • If your URL is a variable then why you are stringifying it. It should be like

    string url = URL + "?dd={{Some Json Data}}&accessKey=ddfr54r5g5r";
    

    Again no need of instantiating a DataContractJsonSerializer for desrializing the data. Rather use Newtonsoft.Json and call the DeserializeObject() method like var data = JsonConvert.DeserializeObject<RootObject>(jsonData);

    I would suggest to use System.Net.Http.HttpClient class rather which gives more control. Something like

       using (HttpClient client = new HttpClient())
       {
          try   
          {
             string responseBody = await client.GetStringAsync(uri);
             var data = JsonConvert.DeserializeObject<RootObject>(responseBody);         
          }  
          catch(HttpRequestException e)
          {
              //log exception
          }
       }
    

    See https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client to get more idea on this