C#: Connect to WebService

(Last Updated On: )

If you need to connect to a webservice method from your C# application you can do as an example like the following below. Notice I also use Newtonsoft for handling the json return. But you can do it however you want depending on your needs. This is just one way of doing it.

  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System.Net.Http;
  4.  
  5. string webserviceURL = "http://whatevermyurlis.com/";
  6. string data = String.Format("my_id={0}", myId);
  7. string url = String.Format("{0}MyMethodName?{1}", webserviceURL, data);
  8. System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
  9. client.BaseAddress = new System.Uri(url);
  10. client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
  11.  
  12. System.Net.Http.HttpContent content = new StringContent("", UTF8Encoding.UTF8, "application/json");
  13. HttpResponseMessage messge = client.PostAsync(url, content).Result;
  14. if (messge.IsSuccessStatusCode)
  15. {
  16.       string result = messge.Content.ReadAsStringAsync().Result;
  17.       JObject jObject = JObject.Parse(result);
  18. }