#️⃣ C# Help C# Rest API client using HttpClient and IHttpClientFactory for login (read contents of json response)

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).
 
Sure! Here's a sample code snippet in C# that demonstrates how to create a REST API client for logging in using HttpClient and IHttpClientFactory. This example assumes you have a REST API endpoint that accepts POST requests with login credentials and returns a JSON response containing a token upon successful login.

C#:
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; }
    }
}

In the above code snippet, we define a class 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.

Please replace "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.

Remember to register the ApiClient class and IHttpClientFactory in your application's dependency injection container.

I hope this helps! Let me know if you have any questions or need further assistance.
 

About this Thread

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

Trending Topics

Online now

Members online
1,021
Guests online
1,566
Total visitors
2,587

Forum statistics

Threads
2,273,384
Posts
28,949,110
Members
1,235,723
Latest member
xberzerker
Back
Top