Итак, я внедрил HttpClientFactory в свою службу:
Код: Выделить всё
private readonly IHttpClientFactory httpClientFactory;
public ApplicationService(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
this.jsonOptions = new JsonSerializerOptions
{
ReferenceHandler = ReferenceHandler.Preserve,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
}
Код: Выделить всё
// Create a new HttpClient instance from the factory
var httpClient = httpClientFactory.CreateClient("");
Код: Выделить всё
public async Task Add(Application entity)
{
try
{
// Create a new HttpClient instance from the factory
var httpClient = httpClientFactory.CreateClient("ApplicationAPI");
// Make the POST request using HttpClient
var response = await httpClient.PostAsJsonAsync("api/application", entity);
// Check if the response is successful
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadFromJsonAsync();
}
// Log the error message for further investigation
var message = await response.Content.ReadAsStringAsync();
throw new Exception($"Error: {response.StatusCode}, Message: {message}");
}
catch (HttpRequestException httpEx)
{
// Handle HTTP request exceptions (e.g., network issues)
Console.WriteLine($"HTTP request error: {httpEx.Message}");
throw;
}
catch (Exception ex)
{
// Handle other exceptions
Console.WriteLine($"An error occurred: {ex.Message}");
throw;
}
}
Код: Выделить всё
builder.Services.AddHttpClient();
Я попытался перейти с HttpClient на HttpClientFactory, но возникла ошибка, указывающая на недопустимый URI. Я ищу решение.
Подробнее здесь: https://stackoverflow.com/questions/790 ... is-invalid