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

时间:2018-10-21 17:27:00

标签: c# .net-core .net-core-2.1

工具

  • Visual Studio 2017专业版(15.8.7)
  • dotnetcore SDK 2.1.403

场景

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

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

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

问题

我已经将IHttpClientFactory添加到了一个类中,但是Visual Studio只选择System.Net.Http命名空间作为建议的参考:

enter image description here

问题

我做错了什么:S

3 个答案:

答案 0 :(得分:2)

Microsoft.Extensions.Http(默认包含在Microsoft.AspNetCore.App软件包中)包含许多通常用于与HTTP相关的代码的软件包,例如,它包含System.Net软件包。 / p>

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

因此,这里没有什么错。只需将using System.Net.Http;添加到您的班级即可。

答案 1 :(得分:2)

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

    }

}

希望获得帮助

答案 2 :(得分:0)

将此包引用添加到您的csproj中。

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