IHttpClientFactory in .NET Core 2.1 Console App references System.Net.Http
Asked Answered
L

3

14

Tools

  • Visual Studio 2017 Professional (15.8.7)
  • dotnetcore SDK 2.1.403

Scenario

I'm attempting to create a console app using the dotnet core framework. The console app needs to make API requests.

I've read about the new IHttpClientFactory released as part of dotnet core 2.1.

The official documenation suggests that all I need to add to my project is a reference to the Microsoft.Extensions.Http NuGet package. I've done this.

Problem

I've added the IHttpClientFactory to a class, but visual studio only picks up the System.Net.Http namespace as a suggested reference:

enter image description here

Question

What did I do wrong :S

Lucchesi answered 21/10, 2018 at 17:27 Comment(0)
G
28

The official documenation suggests that all I need to add to my project is a reference to the Microsoft.Extensions.Http NuGet package. I've done this.

That's true but in order to make things easier, you have to add Microsoft.Extensions.DependencyInjection as a NuGet package, in fact, you can delegate all the creation of httpClient instance to the HttpClientBuilderExtensions which add a lot of extensions methods to create a named or typed HTTPClient here I have written an example for you

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;


namespace TypedHttpClientConsoleApplication
{
    class Program
    {
        public static void Main(string[] args) => Run().GetAwaiter().GetResult();
        public static async Task Run()
        {
            var serviceCollection = new ServiceCollection();


            Configure(serviceCollection);

            var services = serviceCollection.BuildServiceProvider();

            Console.WriteLine("Creating a client...");
            var github = services.GetRequiredService<GitHubClient>();

            Console.WriteLine("Sending a request...");
            var response = await github.GetJson();

            var data = await response.Content.ReadAsStringAsync(); 
            Console.WriteLine("Response data:");
            Console.WriteLine((object)data);

            Console.WriteLine("Press the ANY key to exit...");
            Console.ReadKey();
        }
        public static void Configure(IServiceCollection services)
        {







            services.AddHttpClient("github", c =>
            {
                c.BaseAddress = new Uri("https://api.github.com/");

                c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); // GitHub API versioning
                c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); // GitHub requires a user-agent
            })                        
            .AddTypedClient<GitHubClient>();
        }
        private class GitHubClient
        {
            public GitHubClient(HttpClient httpClient)
            {
                HttpClient = httpClient;
            }

            public HttpClient HttpClient { get; }

            // Gets the list of services on github.
            public async Task<HttpResponseMessage> GetJson()
            {
                var request = new HttpRequestMessage(HttpMethod.Get, "/");

                var response = await HttpClient.SendAsync(request).ConfigureAwait(false);
                response.EnsureSuccessStatusCode();

                return response;
            }
        }

    }

}

Hope this help

Galenical answered 21/10, 2018 at 18:2 Comment(1)
I think the code that adds Github-specific configuration should be a static member of class GitHubClient instead of an anonymous lambda in Configure. Just imo.Wellfixed
C
9

The Microsoft.Extensions.Http, which is default included in the Microsoft.AspNetCore.App package, contains lots of packages which is commonly used for http-related code, it includes the System.Net package for example.

When you use something from the nested packages of Microsoft.Extensions.Http, you still need to reference them by the using statement.

So, nothing is wrong here. Just add a the using System.Net.Http; to your class.

Conte answered 21/10, 2018 at 17:50 Comment(1)
I think you are missing the Microsoft.Extensions.DependencyInjection which make things easierGalenical
G
2

Add this package reference in your csproj.

<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.2" />
Grasshopper answered 16/9, 2019 at 4:25 Comment(1)
This helped me, although I needed a later version number <PackageReference Include="Microsoft.AspNetCore.App" Version="3.1.3" />Urticaria

© 2022 - 2024 — McMap. All rights reserved.