Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

To register HttpClient service in configure service to call api from web application

$
0
0

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. But I want to  call the API repository by registering the client in configure service. So I would like to register the  client service as given below. Is it possible. If possible how can i call the API from repository, Please can you help me

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;
        }


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>