.NET Core 2.1 控制台应用程序引用中的 IHttpClientFactory System.Net.Http

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

工具

场景

我正在尝试使用 dotnet 核心框架创建控制台应用程序。控制台应用程序需要发出 API 请求。

我读到了作为 dotnet core 2.1 的一部分发布的新 IHttpClientFactory

official documenation 表明我需要添加到我的项目中的是对 Microsoft.Extensions.Http NuGet 包的引用。我已经做到了。

问题

我已将 IHttpClientFactory 添加到 class,但 visual studio 仅选择 System.Net.Http 命名空间作为建议参考:

问题

我做错了什么:S

默认包含在Microsoft.AspNetCore.App包中的Microsoft.Extensions.Http包含了很多常用的http相关代码的包,例如System.Net包.

当您使用 Microsoft.Extensions.Http 嵌套 包中的内容时,您仍然需要通过 using 语句 引用它们.

所以,这里没有错。只需将 using System.Net.Http; 添加到您的 class.

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.

没错,但是为了让事情更简单,你必须添加 Microsoft.Extensions.DependencyInjection 作为 NuGet 包,事实上,你可以将所有 httpClient 实例的创建委托给添加的 HttpClientBuilderExtensions许多扩展方法来创建 named or typed HTTPClient 这里我给你写了一个例子

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

    }

}

希望对您有所帮助

在您的 csproj 中添加此包引用。

<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.2" />