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.

 using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;

string webserviceURL = "http://whatevermyurlis.com/";
string data = String.Format("my_id={0}", myId);
string url = String.Format("{0}MyMethodName?{1}", webserviceURL, data);
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

System.Net.Http.HttpContent content = new StringContent("", UTF8Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync(url, content).Result;
if (messge.IsSuccessStatusCode)
{
      string result = messge.Content.ReadAsStringAsync().Result;
      JObject jObject = JObject.Parse(result);
}