Api

 

---


Step-by-Step: API Call with Bearer Token Header



---


✅ STEP 1: Add a Config Class for Token (Optional but Clean)


File: AppConfig.cs (root folder)


namespace ApiConsoleApp

{

    public static class AppConfig

    {

        // You can load this from config file or env variable too

        public static string BearerToken = "YOUR_DYNAMIC_BEARER_TOKEN_HERE";

        public static string ApiBaseUrl = "https://your-api-base-url.com/";

    }

}



---


✅ STEP 2: Modify API Client to Use Bearer Token


File: ApiClients/UserApiClient.cs


using System;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Text;

using System.Threading.Tasks;

using ApiConsoleApp.Models;

using Newtonsoft.Json;


namespace ApiConsoleApp.ApiClients

{

    public class UserApiClient

    {

        private readonly HttpClient _httpClient;


        public UserApiClient()

        {

            _httpClient = new HttpClient

            {

                BaseAddress = new Uri(AppConfig.ApiBaseUrl)

            };

        }


        private void SetHeaders()

        {

            _httpClient.DefaultRequestHeaders.Clear();

            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppConfig.BearerToken);

        }


        public async Task GetUserAsync()

        {

            SetHeaders();


            var response = await _httpClient.GetAsync("api/users/1");

            var content = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Response: {content}");

        }


        public async Task CreateUserAsync(UserModel user)

        {

            SetHeaders();


            var json = JsonConvert.SerializeObject(user);

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


            var response = await _httpClient.PostAsync("api/users", content);

            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Response: {responseContent}");

        }

    }

}



---


✅ STEP 3: Set Token & Call APIs from Main


File: Program.cs


using System;

using System.Threading.Tasks;

using ApiConsoleApp.ApiClients;

using ApiConsoleApp.Models;


namespace ApiConsoleApp

{

    class Program

    {

        static async Task Main(string[] args)

        {

            // Set Bearer Token (in real case, fetch from login API or env)

            AppConfig.BearerToken = "your_actual_token_here";


            var api = new UserApiClient();


            await api.GetUserAsync();


            var newUser = new UserModel

            {

                Id = 2,

                Name = "John Doe"

            };

            await api.CreateUserAsync(newUser);


            Console.ReadLine();

        }

    }

}



---


✅ Folder Structure (Final)


ApiConsoleApp/

├── ApiClients/

│ └── UserApiClient.cs

├── Models/

│ └── UserModel.cs

├── AppConfig.cs

└── Program.cs



---

Perfect! Let's update the project to load the Bearer token from environment variables, which is secure and production-friendly.


Step-by-Step: Use Environment Variable for Bearer Token


STEP 1: Set Environment Variable (Manually)

Option A: In Windows (for testing)

Open Command Prompt or PowerShell:

setx BEARER_TOKEN "your_actual_bearer_token_here"

Restart Visual Studio after setting this.

Option B: Temporarily set in PowerShell before running

$env:BEARER_TOKEN = "your_actual_bearer_token_here"

STEP 2: Update AppConfig.cs to Read from Environment

File: AppConfig.cs

using System;

namespace ApiConsoleApp
{
    public static class AppConfig
    {
        public static string BearerToken => Environment.GetEnvironmentVariable("BEARER_TOKEN");
        public static string ApiBaseUrl => "https://your-api-base-url.com/";
    }
}

Now BearerToken will be read directly from your environment variable named BEARER_TOKEN.


STEP 3: No Changes in Program.cs

using System;
using System.Threading.Tasks;
using ApiConsoleApp.ApiClients;
using ApiConsoleApp.Models;

namespace ApiConsoleApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var api = new UserApiClient();

            await api.GetUserAsync();

            var newUser = new UserModel
            {
                Id = 2,
                Name = "John Doe"
            };
            await api.CreateUserAsync(newUser);

            Console.ReadLine();
        }
    }
}

STEP 4: Error Handling (Optional)

Add a check in UserApiClient.cs to ensure token is set:

private void SetHeaders()
{
    if (string.IsNullOrEmpty(AppConfig.BearerToken))
    {
        throw new InvalidOperationException("Bearer token is not set in environment variables.");
    }

    _httpClient.DefaultRequestHeaders.Clear();
    _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppConfig.BearerToken);
}

Need to Set Variables in Production or Debug?

Let me know if you're deploying or debugging locally and I can show you how to inject env variables in Visual Studio launch settings, app.config fallback, or Azure DevOps / CI/CD pipelines.


Comments

Popular posts from this blog

String Program in C#

CSV using XmlNode

Controller_Model. cs