To consume web APIs in C# (or any other .NET language), you can use the HttpClient class from the System.Net.Http namespace. This class provides methods to send HTTP requests and receive HTTP responses.

Here is an example of how to consume a web API using HttpClient in C#:

“`csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
static async Task Main(string[] args)
{
// Create a new HttpClient instance
using (HttpClient client = new HttpClient())
{
try
{
// Send a GET request to the API endpoint
HttpResponseMessage response = await client.GetAsync(“https://api.example.com/endpoint”);

// Check if the request was successful (HTTP status code 200-299)
if (response.IsSuccessStatusCode)
{
// Read the response content as a string
string responseBody = await response.Content.ReadAsStringAsync();

// Do something with the response
Console.WriteLine(responseBody);
}
else
{
// Print the HTTP status code if the request was not successful
Console.WriteLine($”HTTP Error: {response.StatusCode}”);
}
}
catch (Exception ex)
{
// Print any exception that occurred
Console.WriteLine($”Error: {ex.Message}”);
}
}
}
}
“`

In the above example, we create a new instance of HttpClient and use its GetAsync method to send a GET request to the API endpoint. We then check the response status code to determine if the request was successful. If it was, we read the response content as a string using the ReadAsStringAsync method and do something with it. If the request was not successful, we print the HTTP status code. Finally, we handle any exceptions that occurred during the request process.