#️⃣ 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
  • 370
    Views
  • 1
    Participants
Last reply from:
Unknown user

Trending Topics

Online now

Members online
1,145
Guests online
1,041
Total visitors
2,186

Forum statistics

Threads
2,283,997
Posts
29,019,507
Members
1,220,737
Latest member
zxnxer
Back
Top