41 lines
1.2 KiB
C#
41 lines
1.2 KiB
C#
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Threading.Tasks;
|
|
using System.Xml.Linq;
|
|
|
|
namespace RhSolutions.Services;
|
|
|
|
public class CurrencyClient : ICurrencyClient
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private const string _requestAddress = @"https://www.cbr.ru/scripts/XML_daily.asp?date_req=";
|
|
public HttpStatusCode StatusCode { get; private set; }
|
|
|
|
public CurrencyClient(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<decimal?> GetCurrencyCourse(DateTime date)
|
|
{
|
|
string request = $"{_requestAddress}{date.Date:dd/MM/yyyy}";
|
|
HttpResponseMessage response = await _httpClient.GetAsync(request);
|
|
try
|
|
{
|
|
response.EnsureSuccessStatusCode();
|
|
string xml = await response.Content.ReadAsStringAsync();
|
|
XElement valCourses = XElement.Parse(xml);
|
|
|
|
decimal? exchangeRate = decimal.Parse(valCourses.Elements("Valute")
|
|
.Where(e => e.Element("Name").Value == "Евро")
|
|
.FirstOrDefault()
|
|
.Element("Value").Value);
|
|
return exchangeRate;
|
|
}
|
|
catch
|
|
{
|
|
StatusCode = response.StatusCode;
|
|
return null;
|
|
}
|
|
}
|
|
} |