These days, in order to retrieve data or carry out operations, programs frequently need to communicate with external APIs. GraphQL endpoints, RESTful services, and other kinds of web services are all strongly supported by ASP.NET Core when it comes to API consumption.
Using an API in an ASP.NET Core application will be demonstrated in this tutorial. Starting with project setup and moving on to HTTP request and response handling, we'll go over the fundamentals.
Before starting, ensure you have the following:
Open Visual Studio and select Create a new project.
Choose ASP.NET Core Web Application template.
Provide a name for your project, choose a location, and click Create.
Select ASP.NET Core Web App template with ASP.NET Core 5.0 (or latest version).
In your project, define a model that represents the structure of data you expect to receive from the API. For example, if your API returns user data, create a UserDTO
class:
public class AccessDTO
{
public int Status { get; set; }
public string status_message { get; set; }
public List UserDTO Data { get; set; }
}
public class UserDTO
{
public int Id { get; set; }
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Email { get; set; }
public string? DepartmentName { get; set; }
public string? PositionName { get; set; }
public string? Street { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? Qualification { get; set; }
public string? ZipCode { get; set; }
public decimal Salary { get; set; }
public DateTime HireDate { get; set; }
public DateTime BirthDate { get; set; }
public string? Phone { get; set; }
public string? EmergencyContactName { get; set; }
public string? EmergencyContactPhone { get; set; }
public string IsActive { get; set; }
public DateTime JoiningDate { get; set; }
public DateTime? ResignationDate { get; set; }
public DateTime LastPromotionDate { get; set; }
}
Ensure your project has the necessary packages installed to handle JSON serialization and make HTTP requests. If not already present, install Newtonsoft.Json and System.Net.Http.Json via NuGet Package Manager or using the Package Manager Console:
dotnet add package Newtonsoft.Json
dotnet add package System.Net.Http.Json
Create a service class to encapsulate the logic for making HTTP requests to the API. Here’s an example of a UserService
class:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class UserService
{
private readonly HttpClient _httpClient;
public UserService(HttpClient httpClient)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
public async Task<List<UserDTO>> GetUsersAsync()
{
List<UserDTO> users = new List<UserDTO>();
try
{
HttpResponseMessage response = await _httpClient.GetAsync("https://api.example.com/users");
response.EnsureSuccessStatusCode(); // Throw if not success
string responseBody = await response.Content.ReadAsStringAsync();
users = JsonConvert.DeserializeObject<List<UserDTO>>(responseBody);
}
catch (Exception ex)
{
// Handle exceptions (log, throw, etc.)
Console.WriteLine($"Error: {ex.Message}");
}
return users;
}
}
In your Startup.cs
file, register HttpClient and any services you've created:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<UserService>(client =>
{
client.BaseAddress = new Uri("https://api.example.com/");
// Add any default headers, timeouts, etc. here
});
// Add other services as needed
services.AddControllersWithViews();
}
Inject the UserService
into your controller and use it to fetch data from the API:
public class HomeController : Controller
{
private readonly UserService _userService;
public HomeController(UserService userService)
{
_userService = userService ?? throw new ArgumentNullException(nameof(userService));
}
public async Task<IActionResult> Index()
{
List<UserDTO> users = await _userService.GetUsersAsync();
return View(users);
}
}
Create a view (Index.cshtml
) to display the data retrieved from the API:
@model List<UserDTO>
<h1>Users</h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<!-- Add more columns as needed -->
</tr>
</thead>
<tbody>
@foreach (var user in Model)
{
<tr>
<td>@user.Id</td>
<td>@user.FirstName</td>
<td>@user.LastName</td>
<!-- Add more columns as needed -->
</tr>
}
</tbody>
</table>
Run your ASP.NET Core application and navigate to the appropriate route (e.g., /Home/Index
).
Verify that data from the API is correctly fetched and displayed in your view.
In this guide, we've covered the essential steps for consuming an API in ASP.NET Core. By following these steps, you can effectively integrate external data sources into your applications, leveraging the power and flexibility of ASP.NET Core's HTTP client capabilities.
Now, you have a comprehensive guide that developers can follow to integrate API consumption into their ASP.NET Core applications effectively. Adjust and expand upon these steps based on your specific API requirements and project needs.