using CPRNIMS.Domain.UIContracts.Common; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace CPRNIMS.Domain.UIServices.Common { public class ApiConfigurationService : IApiConfigurationService { private readonly IConfiguration _configuration; public string BaseUrl => _configuration["CommonEndpoints:ApiDefaultHeaders:BaseUrl"]; public ApiConfigurationService(IConfiguration configuration) { _configuration = configuration; } public HttpClient CreateHttpClientWithDefaultHeaders(string token) { if (_configuration == null) { throw new InvalidOperationException("_apiConfigurationService is not configured."); } if (string.IsNullOrEmpty(BaseUrl)) { throw new InvalidOperationException("BaseUrl is not configured."); } var httpClient = new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true }) { BaseAddress = new Uri(BaseUrl) }; var defaultHeaders = DefaultHeaders; httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var customHeaders = CustomHeaders; foreach (var header in customHeaders) { httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); } return httpClient; } public Dictionary DefaultHeaders { get { var headersSection = _configuration.GetSection("CommonEndpoints:ApiDefaultHeaders"); var headers = new Dictionary(); foreach (var childSection in headersSection.GetChildren()) { headers[childSection.Key] = childSection.Value; } return headers; } } public Dictionary CustomHeaders { get { var headersSection = _configuration.GetSection("CommonEndpoints:CustomApiHeaders"); var headers = new Dictionary(); foreach (var childSection in headersSection.GetChildren()) { headers[childSection.Key] = childSection.Value; } return headers; } } } }