On the basis of the daily exchange rate data of the CB (https://ww.cbr-xml-daily.ru/daily_json.js) it is necessary to create a Web-service using ASP.Net Core, which implements 2 API methods:
GET /currencies
- should return the list of currencies with the possibility of paginationGET /currency/
- must return the exchange rate for the transferred currency identifier
I want to know what mistakes I have. What should I fix and how?
Class (and interface) who parsing website (Register as transient):
public interface ICurrentCurrency
{
Task<IEnumerable<Valute>> GetCurrencies();
}
public class CurrentCurrency : ICurrentCurrency
{
public async Task<IEnumerable<Valute>> GetCurrencies()
{
HttpClientHandler handler = new HttpClientHandler();
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;
var client = new HttpClient(handler);
var content = await client.GetAsync("https://www.cbr-xml-daily.ru/daily_json.js");
string json = await content.Content.ReadAsStringAsync();
var obj = JObject.Parse(json)["Valute"].ToString();
return JsonConvert.DeserializeObject<Dictionary<string, Valute>>(obj).Select(x => x.Value);
}
}
In Main
(.NET 6 syntax):
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddTransient<ICurrentCurrency, CurrentCurrency>();
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.UseRouting();
app.Run();
Model:
public class Valute
{
[JsonProperty("ID")]
public string Id { get; set; }
public string Name { get; set; }
public string CharCode { get; set; }
public string NumCode { get; set; }
public int Nominal { get; set; }
public decimal Value { get; set; }
public decimal Previous { get; set; }
}
Class for pagination:
public class CurrencyPageParameters
{
public const int MaxPageSize = 5;
public int PageNumber { get; set; } = 1;
public int _pageSize;
public int PageSize
{
get => _pageSize;
set => _pageSize = (value > MaxPageSize) ? MaxPageSize : value;
}
}
And controller:
[ApiController]
[Route("[action]")]
public class CbrCurrencyController : ControllerBase
{
private ICurrentCurrency _currency;
public CbrCurrencyController(ICurrentCurrency currency)
{
_currency = currency;
}
[HttpGet]
[ActionName("currency")]
public async Task<Valute> GetCurrency(string id)
{
var item = (await _currency.GetCurrencies()).FirstOrDefault(x => x.Id == id);
return item;
}
[HttpGet]
[ActionName("currencies")]
public async Task<IEnumerable<Valute>> Currencies([FromQuery] CurrencyPageParameters @params)
{
var data = (await _currency.GetCurrencies()).Skip((@params.PageNumber - 1) * @params.PageSize).Take(@params.PageSize);
return data;
}
}