Nwanguma Victor
Posted on June 14, 2022
This ReUsable UseFetch Utility used for API data fetching, it can serialize and deserialize objects on the fly.
Headers
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
Class
public static class UseFetch
{
public static TResponse Get<TResponse>(string url,
Dictionary<string, string> headers = null)
where TResponse : class
{
try
{
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
var response = client.GetAsync(url).Result;
var responseString = response.Content.ReadAsStringAsync().Result;
var deserializedResponse = JsonConvert.DeserializeObject<TResponse>(responseString);
return deserializedResponse;
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
public static TResponse Post<TResponse, TRequest>(string url, TRequest request,
Dictionary<string, string> headers = null)
where TRequest : class, new()
where TResponse : class
{
try
{
var serializeRequest = JsonConvert.SerializeObject(request);
var content = new StringContent(serializeRequest);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
var response = client.PostAsync(url, content).Result;
var responseString = response.Content.ReadAsStringAsync().Result;
var deserializedResponse = JsonConvert.DeserializeObject<TResponse>(responseString);
return deserializedResponse;
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
}
}
enjoy 🚀
💖 💪 🙅 🚩
Nwanguma Victor
Posted on June 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
csharp Why Span<T> and Ref Structs Can't Directly Participate in Asynchronous Operations
November 26, 2024