User-1355965324 posted
I am calling the API from my web application is as given below
public class AuthorRepositoryGUI : IAuthorRepositoryGUI
{
private readonly IHttpClientFactory _clientFactory;
public AuthorRepositoryGUI(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
}
public async Task<AuthorDto> GetAuthors()
{
var url = "http://localhost:2318/api/Authors/"
AuthorDto author = new AuthorDto();
var request = new HttpRequestMessage(HttpMethod.Get, url);
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AuthorDto>(jsonString);
}
It is working fine right now.
Is it possible to register the HTTP client in configure service rather than service controller and then how can use it from service controller Please you help me with suggested code
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<IAuthorRepositoryGUI, AuthorRepositoryGUI>(client =>
{
client.BaseAddress = new Uri("https://localhost:44379/");
});
}
// If I create the client in configure service as given above . how can I call the API in the given repository here
public async Task<AuthorDto> GetAuthors()
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AuthorDto>(jsonString);
}
return author;
}