#️⃣ C# Help C# Rest API client using HttpClient and IHttpClientFactory for login

Sure! Below is a sample code for a C# Rest API client using HttpClient and IHttpClientFactory to perform a login operation with the given credentials (API key, username, and password) using a POST method:

C#:
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class ApiClient
{
    private readonly IHttpClientFactory _clientFactory;

    public ApiClient(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task<string> LoginAsync(string apiKey, string username, string password)
    {
        var request = new
        {
            ApiKey = apiKey,
            Username = username,
            Password = password
        };

        var client = _clientFactory.CreateClient();

        var jsonRequest = JsonSerializer.Serialize(request);
        var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

        var response = await client.PostAsync("https://api.example.com/login", content);

        if (response.IsSuccessStatusCode)
        {
            var jsonResponse = await response.Content.ReadAsStringAsync();
            return jsonResponse;
        }
        else
        {
            throw new HttpRequestException($"Failed to login. Status code: {response.StatusCode}");
        }
    }
}

// Usage
public class Program
{
    public static async Task Main()
    {
        var clientFactory = new HttpClientFactory();
        var apiClient = new ApiClient(clientFactory);

        string apiKey = "your_api_key";
        string username = "your_username";
        string password = "your_password";

        try
        {
            var response = await apiClient.LoginAsync(apiKey, username, password);
            Console.WriteLine(response);
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

In this code snippet:

1. The ApiClient class is responsible for making the API call to the login endpoint using HttpClient.
2. The LoginAsync method takes the API key, username, and password as input, serializes them into a JSON object, prepares the request content, and sends a POST request to the login endpoint.
3. The Program class demonstrates how to use the ApiClient by creating an instance, providing the credentials, and calling the LoginAsync method to perform the login operation.
4. Replace "https://api.example.com/login" with the actual login endpoint URL.
5. Replace "your_api_key", "your_username", and "your_password" with the actual API key, username, and password values.

Make sure to handle exceptions and error cases in your production code as needed.
 

About this Thread

  • 1
    Replies
  • 359
    Views
  • 1
    Participants
Last reply from:
Unknown user

Trending Topics

Online now

Members online
1,041
Guests online
1,526
Total visitors
2,567

Forum statistics

Threads
2,273,387
Posts
28,949,158
Members
1,235,726
Latest member
Tempest21
Back
Top