Free Web Development Online Tutorials, Learn to Code
Consume Web API from C# Console Application, Setting Authorization Header of HttpClient

Consume Web API from C# Console Application

In this tutorial, you will learn how to call web api from C# console application, you also learn how to Set Authorization Header of HttpClient.

Call Web API from C# Console Application

First, we create a simple console application, and then we see how to call secure and non-secure web API methods from C# code.

Let’s create a class called APITest in our console application and write following functions to consume Web API with authentication and anonymously.

Call web API using WebClient

Now following function consume the Web API anonymously, it calls the default get function of web API

So, in following function I could have written client.DownloadString(APIUrl+"get"), the result would have been same, the function would return a json string of order items.

private static string APIUrl = "http://localhost:7005/orderapi/";
public static void GetDataWithoutAuthentication() {
using (var client = new WebClient()) {
client.Headers.Add("Content-Type:application/json"); client.Headers.Add("Accept:application/json"); var result = client.DownloadString(APIUrl);   
        Console.WriteLine(Environment.NewLine + result);
    }
}

Call web API using HttpClient

The same above function can be written using HttpClient instead of WebClient

Here are some important reasons why we should use HttpClient instead of WebClient.

  • Http­Client is more closer to HTTP than Web­Client
  • Single HttpClient can make concurrent requests
  • All IO methods are asynchronous in HTTPClient
  • WebClient is in older vversion, HTTPClient is available in .net 4.5 and above

Note: there are some methods like "progress reporting for downloads", "FTP supports" are available in WebClient, which are not there in HttpClient.

private static string APIUrl = "http://localhost:7005/orderapi/";
public static async void GetDataWithoutAuthentication()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(APIUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = await client.GetAsync(APIUrl);

        if (response.IsSuccessStatusCode)
        {
            var readTask = response.Content.ReadAsStringAsync().ConfigureAwait(false);
            var rawResponse = readTask.GetAwaiter().GetResult();
            Console.WriteLine(rawResponse);
        }
        Console.WriteLine("Complete");
    }
}

Above methods does not need any authentication, means anyone who has the API url can consume those methods and get the order item details, but that can be dangerous for real-time business scenario.

So, the API providers make it secure with some credentials, so that only authorize user can have access.

Setting Authorization Header of HttpClient

Now we learn how to set authorization header with given credential tokens.

First, we need to create a credential token with some username and password like one line code below.

var authCredential = Encoding.UTF8.GetBytes("{userTest}:{passTest}");

Now we set the Web API basic authentication details in Header

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authCredential));
private static string APIUrl = "http://localhost:7005/orderapi/";
public static async Task GetDataWithAuthentication()
{
    var authCredential = Encoding.UTF8.GetBytes("{userTest}:{passTest}");
    using (var client = new HttpClient())   
    {
                
                
        client.DefaultRequestHeaders.Authorization = 
            new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authCredential));
        client.BaseAddress = new Uri(APIUrl);
        HttpResponseMessage response = await client.GetAsync(APIUrl+"GetOrders");

        if (response.IsSuccessStatusCode)
        {
            var readTask = response.Content.ReadAsStringAsync().ConfigureAwait(false);
            var rawResponse = readTask.GetAwaiter().GetResult();
            Console.WriteLine(rawResponse);
        }
        Console.WriteLine("Complete");
    }
}

This can be best way to test Web API basic authentication, as a web API developer you can give clear example to end client about how they should consume your secure web API and set security credentials like username and password in http header.

Web API Post from Console Application C#

First create a instance of business object filling with required data, make sure that the object structure match with expected object structure at API end.

List<OrderItem> items = new List<OrderItem>();
items.Add(new OrderItem() { OrderItemId=1, Quantity=2, Description="Rice" });
items.Add(new OrderItem() { OrderItemId = 1, Quantity = 2, Description = "Chicken Curry" });

Order ordermodel = new Order();
ordermodel.ContactPerson = "AC";
ordermodel.Description = "Urgent Order";
ordermodel.GrandTotalPrice = (decimal)180.24;
ordermodel.OrderId = 10;
ordermodel.MobileNumber = "902059598";
ordermodel.OrderStatus = OrderStatus.OrderCreated;
ordermodel.OrderItems = items.ToArray();

Here is the code to serialize your business object and then creating a string content for http context

var dataAsString = JsonConvert.SerializeObject(ordermodel);
var dataContent = new StringContent(dataAsString);

Finally post the object to Web API using PostAsJsonAsync method

Remember, PostAsJsonAsync is the extension method, so you need to install the package AspNetCore.Http.Extensions from Nuget package manager.

HttpResponseMessage response = await client.PostAsJsonAsync(APIUrl + "CreateOrder", dataContent);

Finally, here is the method of posting data to Web API from C# code.

public static async Task PostData()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(APIUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                
        List<OrderItem> items = new List<OrderItem>();
        items.Add(new OrderItem() { OrderItemId=1, Quantity=2, Description="Rice" });
        items.Add(new OrderItem() { OrderItemId = 1, Quantity = 2, Description = "Chicken Curry" });
        Order ordermodel = new Order();
        ordermodel.ContactPerson = "AC";
        ordermodel.Description = "Urgent Order";
        ordermodel.GrandTotalPrice = (decimal)180.24;
        ordermodel.OrderId = 10;
        ordermodel.MobileNumber = "902059598";
        ordermodel.OrderStatus = OrderStatus.OrderCreated;
        ordermodel.OrderItems = items.ToArray();

        var dataAsString = JsonConvert.SerializeObject(ordermodel);
        var dataContent = new StringContent(dataAsString);
        HttpResponseMessage response = await client.PostAsJsonAsync(APIUrl + "CreateOrder", dataContent);
                                 
        if (response.IsSuccessStatusCode)
        {
            Uri ncrUrl = response.Headers.Location;
            Console.WriteLine("Posting Complete");
        }

        Console.WriteLine("Complete");
    }
}

Finally, you can call all above methods from Program.cs file.

Note: there are two methods, Mian and MainAsync, all async methods you can call from MainAsync method using await keyword.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        //APITest.GetDataWithoutAuthentication1();
          
        MainAsync(args).GetAwaiter().GetResult();
        Console.ReadLine();
    }
        
    static async Task MainAsync(string[] args)
    {
        Console.WriteLine("Do Stuff");
        //await APITest.GetDataWithAuthentication();
        await APITest.PostData();
        Console.WriteLine("All Done");
    }
}

You may be interested in following tutorials

Comment
Name
Email
Website
Subscribe
 
Call web API from Console App.

C# web service interview questions


Asp.Net C# Web API Examples | Join Asp.Net MVC Course