Skip to content

Instantly share code, notes, and snippets.

@jpv001
Created July 25, 2014 00:03
Show Gist options
  • Save jpv001/f955d5786814aa42c5c0 to your computer and use it in GitHub Desktop.
Save jpv001/f955d5786814aa42c5c0 to your computer and use it in GitHub Desktop.
Api Calling code - Web API
async void Main()
{
var client = new ApiClient("http://localhost/");
var products = await client.Get<dynamic>("products", MediaType.Json);
}
public class MediaFormatterTypes
{
public MediaTypeFormatter MediaTypeFormatter { get; set; }
public string ContentTypeHeaderValue { get; set; }
}
public class ApiClient
{
private readonly Uri _webApiUri;
private readonly Dictionary<MediaType, MediaFormatterTypes> _formatters = new Dictionary<MediaType, MediaFormatterTypes>
{
{MediaType.Protobuf, new MediaFormatterTypes { MediaTypeFormatter = new ProtoBufFormatter(), ContentTypeHeaderValue = "application/x-protobuf" }},
{MediaType.Json, new MediaFormatterTypes { MediaTypeFormatter = new JsonMediaTypeFormatter(), ContentTypeHeaderValue ="application/json" }}
};
public ApiClient(string serviceUri)
{
_webApiUri = new Uri(serviceUri);
}
public async Task<T> Get<T>(string requestUri, MediaType type = MediaType.Json)
{
using (var client = CreateHttpClient(type))
using (var response = await client.GetAsync(requestUri))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<T>(_formatters.Select(c => c.Value.MediaTypeFormatter));
}
}
private HttpClient CreateHttpClient(MediaType mediaType)
{
client.BaseAddress = _webApiUri;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_formatters[mediaType].ContentTypeHeaderValue));
return client;
}
}
public enum MediaType
{
Protobuf,
Json
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment