Thursday, 4 August 2022

Generic HttpClient

 API Client Base

==========================================

using Newtonsoft.Json;

using System.Text;


namespace APIUtility

{

    public partial class APIClient

    {

        private HttpClientHandler _clientHandler;

        private readonly HttpClient _httpClient;

        private Uri BaseEndpoint { get; set; }


        public APIClient(Uri baseEndpoint)

        {

            if (baseEndpoint == null)

            {

                throw new ArgumentNullException("baseEndpoint");

            }

            BaseEndpoint = baseEndpoint;



            _clientHandler = new HttpClientHandler();

            _clientHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;

            _clientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;

            _httpClient = new HttpClient(_clientHandler);

        }


        /// <summary>  

        /// Common method for making GET calls  

        /// </summary>  

        /// 

        ///Going to attempt to send client cert on this request.



        private async Task<T> GetAsync<T>(Uri requestUrl)

        {

            string data = string.Empty;

            addHeaders();

            try

            {

                var response = _httpClient.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead).Result;


                if (response.IsSuccessStatusCode)

                {

                    data = await response.Content.ReadAsStringAsync();

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }



            return JsonConvert.DeserializeObject<T>(data);

        }



        private async Task<string> GetStringAsync<T>(Uri requestUrl)

        {

            string data = string.Empty;

            addHeaders();

            try

            {

                var response = await _httpClient.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead);


                if (response.IsSuccessStatusCode)

                {

                    data = await response.Content.ReadAsStringAsync();

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }


            return data;

        }


        private async Task<T> DeleteAsync<T>(Uri requestUrl)

        {

            string data = string.Empty;

            addHeaders();

            try

            {

                var response = await _httpClient.DeleteAsync(requestUrl);


                if (response.IsSuccessStatusCode)

                {

                    data = await response.Content.ReadAsStringAsync();

                }

            }

            catch (Exception ex)

            {

                throw ex;

            }


            return JsonConvert.DeserializeObject<T>(data);

        }


        /// <summary>  

        /// Common method for making POST calls  

        /// </summary>  

        private async Task<T> PostAsync<T>(Uri requestUrl, T content)

        {

            addHeaders();

            var x = CreateHttpContent<T>(content);

            var response = _httpClient.PostAsync(requestUrl.ToString(), CreateHttpContent<T>(content)).Result;

            response.EnsureSuccessStatusCode();

            var data = await response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<T>(data);

        }



        private async Task<T1> PostAsync<T1, T2>(Uri requestUrl, T2 content)

        {

            try

            {

                addHeaders();

                var response = _httpClient.PostAsync(requestUrl.ToString(), CreateHttpContent<T2>(content)).Result;

                response.EnsureSuccessStatusCode();

                var data = await response.Content.ReadAsStringAsync();

                return JsonConvert.DeserializeObject<T1>(data);

            }

            catch (Exception ex)

            {

                var s = ex.Message;

                throw;

                

            }

        }


        private async Task<T1> PutAsync<T1,T2>(Uri requestUrl, T2 content)

        {

            addHeaders();

            var response = _httpClient.PutAsync(requestUrl.ToString(), CreateHttpContent<T2>(content)).Result;

            response.EnsureSuccessStatusCode();

            var data = await response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<T1>(data);

        }


        //private async Task<T1> PuttAsync<T1, T2>(Uri requestUrl, T2 content)

        //{

        //    addHeaders();

        //    var response = _httpClient.PutAsync(requestUrl.ToString(), CreateHttpContent<T2>(content)).Result;

        //    response.EnsureSuccessStatusCode();

        //    var data = await response.Content.ReadAsStringAsync();

        //    return JsonConvert.DeserializeObject<T1>(data);

        //}


        private Uri CreateRequestUri(string relativePath, string queryString = "")

        {

            var endpoint = new Uri(BaseEndpoint, relativePath);

            var uriBuilder = new UriBuilder(endpoint);

            uriBuilder.Query = queryString;

            return uriBuilder.Uri;

        }


        private HttpContent CreateHttpContent<T>(T content)

        {

            var json = JsonConvert.SerializeObject(content);

            return new StringContent(json, Encoding.UTF8, "application/json");

        }


        private static JsonSerializerSettings MicrosoftDateFormatSettings

        {

            get

            {

                return new JsonSerializerSettings

                {

                    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat

                };

            }

        }


        private void addHeaders()

        {

            _httpClient.DefaultRequestHeaders.Remove("userIP");

        }

    }

}

using MODELS.Dtos;

namespace APIUtility
{
    public partial class APIClient
    {
        public async Task<List<MessagesDto>> GetMessages(string LkpTag="")
        {
            var requestUrl = CreateRequestUri(string.Format(System.Globalization.CultureInfo.InvariantCulture,
                string.Concat(ApplicationSettings.MessagesRoutePrefix, LkpTag)));
            return await GetAsync<List<MessagesDto>>(requestUrl);
        }

        public async Task<bool> PostMessages(MessagesDto dpDto)
        {
            var requestURL = CreateRequestUri(string.Format(System.Globalization.CultureInfo.InvariantCulture,
                ApplicationSettings.MessagesRoutePrefix));
            return await PostAsync<bool, MessagesDto>(requestURL, dpDto);
        }
        public async Task<bool> PutMessages(MessagesDto dpDto)
        {
            var requestURL = CreateRequestUri(string.Format(System.Globalization.CultureInfo.InvariantCulture,
                ApplicationSettings.MessagesRoutePrefix));
            return await PutAsync<bool,MessagesDto>(requestURL, dpDto);
        }

        // APIClientFactory.Instance.GetApplicationTypes("STATUS").Result
    }
}

Controller
===========================================================

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Text;

namespace Controllers
{
    public class MessageController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public MessageController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            var model = new MessageViewModel();

            return View("Index", model);
        }
        public IActionResult Search()
        {
            var model = new MessageViewModel();

            return View("Search",model);
        }
        public async Task<ActionResult> SearchResult(JQueryDataTableParams param)
        {
            
            var result = APIClientFactory.Instance.GetMessages().Result;
            var displayMinutes = result.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var display = from c in displayMinutes
                         select new object[] { "", c.MessageId,c.Subject,c.Message,c.StartDate,c.EndDate };


            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = result.Count(),
                iTotalDisplayRecords = result.Count(),
                aaData = display
            });
        }


        [HttpGet]
        public async Task<ActionResult> Details(int id)
        {
            try
            {

                var result = APIClientFactory.Instance.GetMessages().Result;
                var model = result.FirstOrDefault(m => m.MessageId == id);
                model.EndDate = Convert.ToDateTime(model.EndDate);
                model.StartDate = Convert.ToDateTime(model.StartDate);

                var viewModel = new MessageViewModel()
                {
                    MessageId = model.MessageId,
                    EndDate = model.EndDate,
                    Message = model.Message,
                    PriorityId = model.PriorityId,
                    StartDate = model.StartDate,
                    Subject = model.Subject
                };

                return View("Index", viewModel);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        [HttpPost]
        public async Task<ActionResult> Update(MessageViewModel model, string action)
        {
           
            var message = new MessagesDto()
            {
                created_by = "",
                created_Date = DateTime.Now,
                EndDate = model.EndDate,
                StartDate = model.StartDate,
                Message = model.Message,
                Subject = model.Subject,
                updated_by = "",
                updated_date = DateTime.Now,
                MessageId = model.MessageId,
                PriorityId = model.PriorityId
            };

            var result = APIClientFactory.Instance.PutMessages(message).Result;
            return RedirectToAction(nameof(Index));
        }

        [HttpPost]
        public async Task<ActionResult> Add(MessageViewModel model)
        {
            try
            {
                var message = new MessagesDto()
                {
                    created_by="",
                    created_Date=DateTime.Now,
                    EndDate=model.EndDate,
                    StartDate=model.StartDate,
                    Message=model.Message,
                    Subject=model.Subject,
                    updated_by="",
                    updated_date=DateTime.Now,
                    MessageId=0,
                    PriorityId=model.PriorityId
                };

                var result = APIClientFactory.Instance.PostMessages(message).Result;
            }
            catch (Exception ex)
            {
                string m = ex.Message;
            }
          


            return RedirectToAction(nameof(Index));
        }



        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}


HttpClient Instance
===============================================

namespace APIUtility
{
    public class APIClientFactory
    {
        private static Uri apiUri;

        private static Lazy<APIClient> restClient;

        static APIClientFactory()
        {
            apiUri = new Uri(ApplicationSettings.WebApiUrl);
            restClient = new Lazy<APIClient>(() => new APIClient(apiUri), LazyThreadSafetyMode.ExecutionAndPublication);
        }

        public static APIClient Instance
        {
            get
            {
                return restClient.Value;
            }
        }
    }
}




No comments:

Post a Comment