Skip to content

Instantly share code, notes, and snippets.

@ahmad2x4
Created September 24, 2012 22:25
Show Gist options
  • Save ahmad2x4/3778821 to your computer and use it in GitHub Desktop.
Save ahmad2x4/3778821 to your computer and use it in GitHub Desktop.
WebApi Call Json
private TResult CallWebApi<TResult, TRequest>(string baseURI, string resource, string method, TRequest request)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseURI);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
TResult response;
HttpResponseMessage responsepromise;
if (method.ToUpper() == "POST")
responsepromise = client.PostAsJsonAsync(resource, request).Result;
else
responsepromise = client.GetAsync(resource).Result;
//var responsepromise = client.GetAsync(resource, request).Result;
if (responsepromise.IsSuccessStatusCode)
{
response = responsepromise.Content.ReadAsAsync<TResult>().Result;
return response;
}
else
{
Console.WriteLine("Api call failed");
throw new Exception();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment