using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace HttpClientSample
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
static HttpClient client = new HttpClient();
static void ShowProduct(Product product)
Console.WriteLine($"Name: {product.Name}\tPrice: " + $"{product.Price}\tCategory: {product.Category}");
static async Task<string> CreateProductAsync(Product product)
string jsonString = JsonSerializer.Serialize(product);
var data = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await client.PostAsync("post", data);
return await response.Content.ReadAsStringAsync();
static async Task<string> GetProductAsync(string query_)
var builder = new UriBuilder(client.BaseAddress + "get");
var url = builder.ToString();
var res = await client.GetAsync(url);
return await res.Content.ReadAsStringAsync();
static async Task<HttpStatusCode> DeleteProductAsync(string id)
HttpResponseMessage response = await client.DeleteAsync($"api/products/{id}");
return response.StatusCode;
RunAsync().GetAwaiter().GetResult();
static async Task RunAsync()
client.BaseAddress = new Uri("http://httpbin.org/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Product product = new Product
Console.WriteLine("Creando producto...");
var string_ = await CreateProductAsync(product);
Console.WriteLine($"Created: {string_}");
Console.WriteLine("Devolviendo producto...");
var creado_ = await GetProductAsync("Id=12");
Console.WriteLine($"Devuelto: {creado_}");
Console.WriteLine(e.Message);