Updated March 29, 2023
Introduction to ASP.NET Core HttpClient
ASP.NET Core HttpClient is used to send the HTTP PATCH requests. By using the HttpClient, we can send the requests of HTTP PATCH to get done the updates of our resources which improves the performance of applications. Furthermore, to improve memory usage and performance, we can make use of the streams with HttpClient.
What ASP.NET Core HttpClient?
The class ASP.NET Core HttpClient, which enables to send of HTTP requests and get the HTTP responses from URI (in which URI identifies the resources). By using the class, we can send entire types of HTTP requests like PATCH, GET, DELETE, POST, PUT, and it accepts responses from the server.
The HttpClient uses the HTTP Message handlers, which are used to send the requests and get the responses, the essential job of the default message handler. Although we can use multiple message handlers and create a pipeline, this HttpClient uses only one message handler. Several handlers manipulate only the headers of the request, and few may work with timeouts and so on.
How can we use ASP.NET Core HttpClient?
ASP.NET Core HttpClient is used to send the HTTP PATCH requests. By using the HttpClient, we can send the requests of HTTP PATCH to get done the updates of our resources. The PATCH request executes by several operations as a part of the JSON array. Let’s see the following PATCH Operations,
Here, the request bodies an array of JSON objects that specify the various operations. The operations specified with the op property, the path part denotes the path to object property which we can modify the name property in the case. Finally, the value part represents the new value used to replace the previous one for the name property.
ASP.NET Core HttpClient Applications
In ASP.NET Core HttpClient Applications, there will be various applications divided into the following sections they are as follows,
- To send POST Request by using HttpClient ASP.NET Core
- To use HttpClient ASP.NET Core for sending PUT Request
- To send DELETE Request with HttpClient
To send POST Request by using HttpClient ASP.NET Core
For sending the POST request using the HttpClient ASP.NET Core, we have the HttpClientCrudService class in the application CompanyEmployees.Client, it contains the methods, we adding the new method for sending the POST request to the application.
private async Task CreateCompany()
{
var companyForCreation = new CompanyForCreationDto
{
Name = "ABC Limited.",
Country = "INDIA",
Address = "Spencer Plaza"
};
var _comp = JsonSerializer.Serialize(companyForCreation);
var req_content = new StringContent(_comp, Encoding.UTF8, "application / json");
var response = await _httpClient.PostAsync("companies", req_content);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var createdCompany = JsonSerializer.Deserialize<CompanyDto>(content, _options);
}
Let’s create the company object which used to create and serialize the method. To create the new StringContent object for providing the serialized company, media type argument, and encoding type. Then, use the PostAsync method, which is used to send the POST request for the application. Once receiving the response, check whether it’s successful. To read the content with the ReadAsStringAsync method for deserializing the content by using the JsonSerializerOptionsargument. To make sure the client app for calling the method,
public async Task Execute()
{
await CreateCompany();
}
Look at the CreateCompany method by setting the breakpoint and seeing the application.
By using the HttpRequestMessage class for sending the POST request, the method called PostAsync encapsulates the HttpRequestMessage class. For the good control over our request, which explicitly set up various request options like the header to make use of HttpRequestMessageClass,
private async Task CreateCompanyWithHttpRequestMessage()
{
var companyForCreation = new CompanyForCreationDto
{
Name = "ABC Ltd,",
Country = "INDIA",
Address = "Spencer Plaza - 65"
};
var company = JsonSerializer.Serialize(companyForCreation);
var request = new HttpRequestMessage(HttpMethod.Post, "companies");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new StringContent(company, Encoding.UTF8);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var createdCompany = JsonSerializer.Deserialize<CompanyDto>(content, _options);
}
To start with the object companyForCreation object and its serialization, to create a new HttpRequestMessage object and give the type request and the endpoint’s address. Then, expand the requested content using the StringContent class and provide the encoding type and serialized company object. Finally, to denote the media type of request with ContentType property.
HttpClient ASP.NET Core for sending PUT Request
Here is the HttpClient of ASP.NET Core for sending the PUT request; in this code, just to mention that our application UpdateCompany action returns the NoContent response. Therefore there will be no content to de-serialize the client-side. To include the new method in HttpClientCrudService class,
private async Task UpdateCompany()
{
var updatedCompany = new CompanyForUpdateDto
{
Name = "ABC Ltd,",
Country = "INDIA",
Address = "Spencer Plaza -5321- Updated"
};
var _comp = JsonSerializer.Serialize(updatedCompany);
var req_Content = new StringContent(_comp, Encoding.UTF8, "application/json");
var uri = Path.Combine("companies", "fc12c11e-33a3-45e2-f11e-08d8bdb38ded");
var response = await _httpClient.PutAsync(uri, req_Content);
response.EnsureSuccessStatusCode();
}
In the included new method, build the updateCompany object with the altered Address property. Then in the method, CreateCompany serializes the object and builds the new StringContent, which provides the serialized object, media type, and encoding type. Finally, create the URI to controller action it supposes expecting the ID of the company, which we updated.
To send the PUT request by using the PutAsync and to make sure that it receives the successful status code. The NoContent status code will be code 204. The altered Execute Method will be
public async Task Execute()
{
...
await UpdateCompany();
}
Look at the UpdateCompany method by setting the breakpoint and seeing the application.
To send DELETE Request with HttpClient
Let’s send the DELETE Request with a shortcut method called DeleteAsync method,
private async Task DeleteCompany()
{
var uri = Path.Combine("companies", "fc12c11e-33a3-45e2-f11e-08d8bdb38ded");
var response = await _httpClient.DeleteAsync(uri);
response.EnsureSuccessStatusCode();
}
For executing the method to make a call from Execute method like as follows,
public async Task Execute()
{
...
await DeleteCompany();
}
When executing the client application, we will be getting the 204 response; it is the applicable response for action Delete.
ASP.NET Core HttpClient examples
Let’s see the ASP.NET Core application by using the HttpClient, creating the library for wrapping the functionality of HttpClient, making use for the builder pattern purpose, and adding the class with methods for methods storing theHttpClinet.
public class HttpRequestBuilder
{
private HttpMethod method = null;
private string requestUri = "";
private HttpContent content = null;
private string bearerToken = "";
private string acceptHeader = "application/json";
private TimeSpan timeout = new TimeSpan(0, 0, 15);
public HttpRequestBuilder()
{
}
public HttpRequestBuilder AddMethod(HttpMethod method)
{
this.method = method;
return this;
}
public HttpRequestBuilder AddRequestUri(string requestUri)
{
this.requestUri = requestUri;
return this;
}
public HttpRequestBuilder AddContent(HttpContent content)
{
this.content = content;
return this;
}
public HttpRequestBuilder AddBearerToken(string bearerToken)
{
this.bearerToken = bearerToken;
return this;
}
public HttpRequestBuilder AddAcceptHeader(string acceptHeader)
{
this.acceptHeader = acceptHeader;
return this;
}
public HttpRequestBuilder AddTimeout(TimeSpan timeout)
{
this.timeout = timeout;
return this;
}
See below the following output as follows,
Conclusion
This article has explained the HttpClient like how to use in the core application and learned about the requests like how to DELETE, PUT, and POST requests from the application. I hope the article helps to understand.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET Core HttpClient” was beneficial to you. You can view EDUCBA’s recommended articles for more information.