using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
public class ApiClient
{
private readonly IHttpClientFactory _clientFactory;
public ApiClient(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<string> LoginAndGetToken(string apiKey, string username, string password)
{
var client = _clientFactory.CreateClient();
var loginData = new
{
ApiKey = apiKey,
Username = username,
Password = password
};
var json = JsonSerializer.Serialize(loginData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("YOUR_LOGIN_ENDPOINT_URL", content);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadFromJsonAsync<LoginResponse>();
return responseContent.Token;
}
public async Task<UserAccountInfo> GetUserAccountInfo(string apiKey, string username, string password)
{
var token = await LoginAndGetToken(apiKey, username, password);
var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
var response = await client.GetAsync("YOUR_USER_INFO_ENDPOINT_URL");
response.EnsureSuccessStatusCode();
var userInfo = await response.Content.ReadFromJsonAsync<UserAccountInfo>();
return userInfo;
}
}
public class LoginResponse
{
public string Token { get; set; }
}
public class UserAccountInfo
{
// Add properties for user account information
}
// Usage example
public async Task Main()
{
var services = new ServiceCollection();
services.AddHttpClient();
var serviceProvider = services.BuildServiceProvider();
var apiClient = new ApiClient(serviceProvider.GetRequiredService<IHttpClientFactory>());
var apiKey = "YOUR_API_KEY";
var username = "YOUR_USERNAME";
var password = "YOUR_PASSWORD";
var userInfo = await apiClient.GetUserAccountInfo(apiKey, username, password);
// Access user account information from userInfo object
}