#️⃣ C# Help C# Rest API client using httpclient for login

Certainly! Below is a sample C# code snippet that demonstrates how to create a REST API client using HttpClient for login using a POST request with login credentials such as API key, username, and password:

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

namespace RestApiClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string apiUrl = "https://api.example.com/login";
            string apiKey = "YOUR_API_KEY";
            string username = "USERNAME";
            string password = "PASSWORD";

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Api-Key", apiKey);

                var loginData = new
                {
                    username = username,
                    password = password
                };

                var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(loginData), Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Login successful! Response: " + responseContent);
                }
                else
                {
                    Console.WriteLine("Login failed. Status code: " + response.StatusCode);
                }
            }
        }
    }
}

In this code snippet:
  • Replace https://api.example.com/login with the actual API endpoint for login.
  • Replace YOUR_API_KEY, USERNAME, and PASSWORD with your actual API key, username, and password.
  • The code sends a POST request with the login credentials in JSON format to the API endpoint.
  • It expects a successful response (HTTP 200) upon successful login.

Make sure you have the Newtonsoft.Json package installed in your project for JSON serialization and deserialization.

Feel free to modify the code as needed based on the specific requirements of your REST API and login endpoint. Let me know if you need further assistance or clarification!
 

About this Thread

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

Trending Topics

Online now

Members online
1,139
Guests online
1,274
Total visitors
2,413

Forum statistics

Threads
2,273,429
Posts
28,949,439
Members
1,235,743
Latest member
lilwar14
Back
Top