DEV Community

Nwanguma Victor
Nwanguma Victor

Posted on

ReUsable UseFetch Utility in C#

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;
Enter fullscreen mode Exit fullscreen mode

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());
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

enjoy šŸš€

Top comments (1)

Collapse
 
kanebarton profile image
Kane Barton

Iā€™d suggest avoiding a custom developed utility class like this as there are some common pitfalls (e.g., HttpClient should be static, correctly using async/await, no transient retries, memory over allocations not using strings) but instead use a more standard library like: System.Net.Http.Json

docs.microsoft.com/en-us/dotnet/ap....