Sitemap
1 min readFeb 23, 2023

--

Secure REST API Requests in .NET with Basic Authentication

Here’s an example of how to use Basic Authentication with a REST API in .NET using HttpClient:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
static async Task Main(string[] args)
{
// Set the API endpoint URL and the credentials
var url = “https://api.example.com/endpoint";
var username = “my_username”;
var password = “my_password”;

// Create the HttpClient instance
var client = new HttpClient();

Get Neeraj Upadhyay’s stories in your inbox

Join Medium for free to get updates from this writer.

// Set the Basic Authentication header
var authHeader = new AuthenticationHeaderValue(“Basic”, Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes($”{username}:{password}”)));
client.DefaultRequestHeaders.Authorization = authHeader;

// Make a GET request to the API endpoint
var response = await client.GetAsync(url);

// Get the response content as a string
var responseContent = await response.Content.ReadAsStringAsync();

// Print the response
Console.WriteLine(responseContent);
}
}

In this example, we create a HttpClient instance and set the Basic Authentication header with the Authorization property. We then make a GET request to the API endpoint with GetAsync and await the response. Finally, we get the response content as a string with ReadAsStringAsync and print it to the console.

--

--

Neeraj Upadhyay
Neeraj Upadhyay

Written by Neeraj Upadhyay

"Experienced full stack developer skilled in web dev, enterprise apps, Git, SonarQube, SQL Azure and Angular. Let's build something great together! 🚀"