public async Task Get()
{
try
{
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("http://localhost:81/myapi/api/api.php"))
{
if (response.IsSuccessStatusCode)
{
string apiResponse = await response.Content.ReadAsStringAsync();
ApiResponse apiResult = JsonConvert.DeserializeObject(apiResponse);
List reservationList = apiResult.Data;
return View(reservationList);
}
else
{
// Handle the case where the API call was not successful
// You might want to log the response status or handle it accordingly
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
return View(new List()); // return an empty list or handle it as per your requirement
}
}
}
}
catch (Exception ex)
{
// Handle any exceptions that occur during the API call
// Log the exception details or handle the error appropriately
ModelState.AddModelError(string.Empty, "Exception occurred while retrieving data from server.");
return View(new List()); // return an empty list or handle it as per your requirement
}
}
APIs, or application programming interfaces, are crucial for interoperability across many technologies in the field of web development. Systems may communicate and share data with ease thanks to APIs, regardless of the framework you're using—Java,.NET, Angular, React, or another one.
This example shows you how to use the HttpClient
in.NET Core to consume an API. You can use this class to handle HTTP replies from a defined URI and send HTTP queries. In this case, we are concentrating on submitting an asynchronous GET request to a specified API endpoint. The implementation ensures strong integration with external APIs in a web application environment by including ways to handle both successful and unsuccessful answers.
Method Declaration:
public async Task<IActionResult> Get()
: This declares a public asynchronous method named Get
that returns an IActionResult
. In ASP.NET Core, methods like these typically handle HTTP requests.
Try-Catch Block:
The entire method is enclosed in a try-catch
block to handle exceptions that might occur during the API call.
HTTP Client Initialization:
using (var httpClient = new HttpClient())
: This creates an instance of HttpClient
, which is used to send HTTP requests and receive HTTP responses from a specified URI.
Sending GET Request:
using (var response = await httpClient.GetAsync("http://localhost:81/myapi/api/api.php"))
: This line sends an asynchronous GET request to the specified URI (http://localhost:81/myapi/api/api.php
). The await
keyword ensures that the method asynchronously waits for the response.
Handling API Response:
if (response.IsSuccessStatusCode)
: Checks if the HTTP response was successful (status code in the 200-299 range).
If successful:
string apiResponse = await response.Content.ReadAsStringAsync();
: Reads the content of the response as a string.ApiResponse apiResult = JsonConvert.DeserializeObject<ApiResponse>(apiResponse);
: Deserializes the JSON response (apiResponse
) into an instance of ApiResponse
using Newtonsoft.Json (JsonConvert
).List<Reservation> reservationList = apiResult.Data;
: Extracts the Data
property from apiResult
, assuming it contains a list of Reservation
objects.return View(reservationList);
: Returns a view (View()
) with reservationList
as the model data.If not successful:
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
: Adds a model error message to indicate a server error.return View(new List<Reservation>());
: Returns a view with an empty list if there's an error.Exception Handling:
catch (Exception ex)
: Catches any exceptions that occur during the execution of the try
block.
ModelState.AddModelError(string.Empty, "Exception occurred while retrieving data from server.");
: Adds a model error message for exception scenarios.return View(new List<Reservation>());
: Returns a view with an empty list if there's an exception.