Add details in implementation class –
private readonly IHttpClientFactory _httpClientFactory;
public BaseService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
Add details in called method
HttpClient client = _httpClientFactory.CreateClient(“MangoAPI”);
HttpRequestMessage message = new();
message.RequestUri = new Uri(“”);
HttpResponseMessage? apiResponse = null;
apiResponse = await client.SendAsync(message);
switch (apiResponse.StatusCode)
{
case HttpStatusCode.NotFound:
return new() { IsSuccess = false, Message = “Not Found” };
case HttpStatusCode.Forbidden:
return new() { IsSuccess = false, Message = “Access Denied” };
case HttpStatusCode.Unauthorized:
return new() { IsSuccess = false, Message = “Unauthorized” };
case HttpStatusCode.InternalServerError:
return new() { IsSuccess = false, Message = “Internal Server Error” };
default:
var apiContent = await apiResponse.Content.ReadAsStringAsync();
var apiResponseDto = JsonConvert.DeserializeObject(apiContent);
return apiResponseDto;
}
Register in Program.cs
builder.Services.AddHttpContextAccessor();
builder.Services.AddHttpClient();