Introduction:
HttpClient is a class in the .NET framework that is commonly used in ASP.NET Web API to send HTTP requests and receive HTTP responses from a remote server. It provides a simple and efficient way to interact with HTTP-based APIs or web services.
- HttpClient allows you to perform various HTTP methods such as GET, POST, PUT, DELETE, etc. It also supports handling headers, query parameters, request and response content, and more.
Here are some key features and functionalities of HttpClient in ASP.NET Web API:
1)Sending HTTP requests:
- You can create an instance of HttpClient and use its methods like GetAsync, PostAsync, PutAsync, DeleteAsync, etc., to send requests to a remote server. These methods return Task, which represents an asynchronous operation that receives an HTTP response.
2)Handling HTTP responses:
- HttpClient allows you to handle the responses received from the remote server. You can check the status code, read response headers, and retrieve the response content using methods like IsSuccessStatusCode, Headers, and ReadAsStringAsync.
3) Handling request and response content:
- HttpClient provides methods to set request headers, set request content, and read response content. You can pass data in the request body using StringContent, FormUrlEncodedContent, or ByteArrayContent, depending on the content type.
4)Configuring HTTP client settings:
⦁ We can customize various aspects of the HttpClient instance, such as setting a timeout, configuring default headers, handling redirects, managing cookies. These settings can be specified using the HttpClientHandler class or by setting properties on the HttpClient instance.
⦁ HttpClient is a powerful and flexible class that simplifies the process of making HTTP requests and handling responses in ASP.NET Web API.
⦁ It is widely used for integrating with external APIs, consuming web services, or implementing client-side communication in a distributed system.
⦁ The HttpClient class in ASP.NET Web API is used to send HTTP requests and receive HTTP responses from a remote server. It provides a way to make HTTP calls to other APIs or web services.
Here is an example of using HttpClient to call an API from another API:
⦁ An instance of HttpClient is created in the constructor of the MyApiController class. The CallExternalApi method demonstrates how to use HttpClient to send an HTTP GET request to the specified API endpoint (apiUrl).
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace HttpClientSample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
private readonly HttpClient _httpClient;
public SampleController()
{
_httpClient = new HttpClient();
}
[HttpGet]
public async Task<string> GetApiResponse(string apiUrl)
{
try
{
HttpResponseMessage response = await _httpClient.GetAsync("https://localhost:7182/api/Stduent");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
return null;
}
}
}
}
⦁ It asynchronously waits for the response and checks if the request was successful by checking the EnsureSuccessStatusCode property of the HttpResponseMessage.
⦁ If the response is successful, the content of the response is read as a string using ReadAsStringAsync. You can then process the response data as needed.
⦁ If the response is not successful, you can handle it by returning an error message or throwing an exception.
⦁ Remember to handle exceptions appropriately to handle network errors, timeouts, or other issues that may occur during the HTTP request.
⦁ Creating a new instance of HttpClient for each request can lead to socket exhaustion under heavy load.
Solution of the HttpClient an Api calling another Api using ApiUrl:
Another Example for using http client to generating Access tokens from Api:
Code:
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using System.Text;
using Newtonsoft.Json;
using System.Net.Http;
using System;
using Microsoft.Graph.Models;
using HttpClientSample.Models;
namespace HttpClientSample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class HttpClientController : ControllerBase
{
private string url = "https://localhost:7137/api/HttpClient";
private string url1 = "https://api.escuelajs.co/api/v1/auth/profile";
[HttpPost]
public async Task<IActionResult> GetAccess(Login login)
{
var httpClient = new HttpClient();
var jsonContent = System.Text.Json.JsonSerializer.Serialize(login);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
var jsonResponse = JsonDocument.Parse(responseContent).RootElement;
var accessToken = jsonResponse.GetProperty("access_token").GetString();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var responses = await httpClient.GetAsync(url1);
if (responses.IsSuccessStatusCode)
{
var responseContents = await responses.Content.ReadAsStringAsync();
var userDetails = JsonConvert.DeserializeObject<Models.User>(responseContents);
return Ok(userDetails);
}
else
{
return BadRequest();
}
}
else
{
return BadRequest();
}
}
}
}
⦁ Here we have used the in-built tokens to show how the http client works.
Use this link for example to run the api:
https://fakeapi.platzi.com/en/rest/auth-jwt
⦁ In this code we have used 2 models
1)Login
2)User
Login Models:
{
public class Login
{
public string Email { get; set; }
public string Password { get; set; }
}
}
User Models:
namespace HttpClientSample.Models
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public string Avatar { get; set; }
}
}
⦁ The url which passes in the Api is the in-built Url from the above link.
⦁ In the code we have used a Json Serialization and Deserialization.
⦁ Json Serialization :
Serialization is the process of converting .NET objects, such as strings, into a JSON format.
var jsonContent = System.Text.Json.JsonSerializer.Serialize(login);
⦁ Json Deserialization:
Deserialization is the process of converting JSON data into .NET objects.
var userDetails = JsonConvert.DeserializeObject(responseContents);
⦁ This sample shows the Http post method, where we have given the login credentials.
⦁ In the first URL we have given the login credentials. It will automatically generate the access tokens which will pass to the url to show the profile user details.
Advantages of HttpClient:
⦁ Simplicity: HttpClient provides a simple and intuitive API for sending HTTP requests and handling responses.
⦁ Asynchronous Support: HttpClient supports asynchronous operations, allowing you to perform non-blocking HTTP requests. This enables better scalability and responsiveness of applications.
⦁ Flexibility: HttpClient offers a wide range of configuration options, allowing you to customize various aspects of the HTTP requests and responses.
⦁ Extensibility: HttpClient can be extended through message handlers, which allow you to intercept and modify HTTP requests and responses.
Disadvantages of HttpClient:
⦁ Connection Management: Improper use of HttpClient can lead to inefficient connection management.
⦁ Lack of Retry Logic: HttpClient does not provide built-in retry logic for handling transient failures, such as network errors or timeouts.
⦁ Versioning and Compatibility: Upgrading to a new version of HttpClient or the underlying .NET framework may introduce breaking changes that require code modifications.
⦁ Testing and Mocking: Testing code that uses HttpClient can be challenging due to its tight coupling with external services. Writing unit tests that don’t rely on actual network connections may require additional effort, such as using mocking frameworks or creating test doubles for HttpClient calls.
Conclusion:
Hence we have created the HttpClient API,using HttpClient we have called an API from another API .Other detailed concepts of Web API will be covered in the upcoming blogs.
No Comment! Be the first one.