Well1AmNichtDiePerson
Established
C# Rest API Client sample code for login using HttpClient and IHttpClientFactory given login (post method) credentials (API key, username, password). Read JSON response (Token).
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class ApiClient
{
private readonly IHttpClientFactory _httpClientFactory;
public ApiClient(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<string> Login(string apiKey, string username, string password)
{
var client = _httpClientFactory.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("https://your-api-endpoint/login", content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var token = JsonSerializer.Deserialize<TokenResponse>(responseContent).Token;
return token;
}
else
{
throw new HttpRequestException($"Failed to login. Status code: {response.StatusCode}");
}
}
private class TokenResponse
{
public string Token { get; set; }
}
}
ApiClient that uses IHttpClientFactory for creating an instance of HttpClient. The Login method sends a POST request to the login endpoint with the provided credentials and reads the JSON response containing the token upon successful login."https://your-api-endpoint/login" with the actual URL of your API endpoint. Additionally, adjust the TokenResponse class to match the structure of the JSON response containing the token.ApiClient class and IHttpClientFactory in your application's dependency injection container.