using System.Globalization;
using System.Net.Http.Headers;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using static System.Console;
public class ExchangeRateResponse
[JsonPropertyName("USDBRL")]
public ExchangeRateData USDBRL { get; set; }
public class ExchangeRateData
[JsonPropertyName("ask")]
public decimal Ask { get; set; }
public class ExchangeRateResponseDTO
public decimal ConvertedAmount { get; set; }
public interface IExchangeRateService
Task<ExchangeRateResponseDTO> GetCurrentExchangeRate(decimal usdValue);
public class ExchangeRateService : IExchangeRateService
private const string ApiUrl = "https://economia.awesomeapi.com.br/last/USD-BRL";
private readonly HttpClient _httpClient;
public ExchangeRateService(HttpClient httpClient)
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")
public async Task<ExchangeRateResponseDTO> GetCurrentExchangeRate(decimal usdValue)
var client = new RestClient();
var request = new RestRequest(ApiUrl);
var response = await client.GetAsync<ExchangeRateResponse>(request);
if (response?.USDBRL == null)
throw new System.Text.Json.JsonException(" Erro ao Pegar cotação da API ");
return new ExchangeRateResponseDTO { ConvertedAmount = response.USDBRL.Ask * usdValue };
catch (System.Text.Json.JsonException ex)
throw new System.Text.Json.JsonException(
$"Erro ao mapear/converter retorno da API = {ex.Message}"
catch (HttpRequestException ex)
throw new HttpRequestException(
$"Falha de requisição, verifique conexão na internet! Detalhe={ex.Message} "
throw new Exception($"Erro inesperado:{ex.Message}!");
public static async Task Main(string[] args)
var services = new ServiceCollection();
services.AddHttpClient();
services.AddTransient<IExchangeRateService, ExchangeRateService>();
var serviceProvider = services.BuildServiceProvider();
var exchangeRateService = serviceProvider.GetRequiredService<IExchangeRateService>();
WriteLine("\n--- Conversor de Dólar para Real ---");
WriteLine("Digite um valor em dólares (USD) ou S para sair:");
string input = ReadLine();
if (input?.ToLower() == "s")
WriteLine("Finalizando aplicativo.");
CultureInfo.InvariantCulture,
"Use um Input numérico válido (numeros maior que zero). ex : 123 ou 100.55 \n"
var convertedValues = await exchangeRateService.GetCurrentExchangeRate(usdValue);
$"\n{usdValue:C2} dólares equivalem a {convertedValues.ConvertedAmount:C2} reais (cotação atual).\n"
catch (FormatException ex)
WriteLine($"Falha ao converter entrada!. {ex.Message}\n ");
catch (System.Text.Json.JsonException ex)
WriteLine($"Houve problema ao obter dados da API . Detalhe: {ex.Message}\n ");
catch (HttpRequestException ex)
WriteLine($"Erro na requisicao ou resposta do Servidor!. detalhes : {ex.Message}\n");
catch (ArgumentNullException ex)
WriteLine($"Um valor do sistema não pode ser nulo , confira :{ex.Message}\n");
$" Ocorreu um Erro inesperado ! Confira logs ou contacte o time!. Message :{ex.Message}\n"