【问题标题】:IHttpClientFactory in .NET Core 2.1 Console App references System.Net.Http.NET Core 2.1 控制台应用程序中的 IHttpClientFactory 引用 System.Net.Http
【发布时间】:2019-03-25 20:36:48
【问题描述】:

工具

  • 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 命名空间作为建议参考:

问题

我做错了什么:S

【问题讨论】:

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


    【解决方案1】:

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

    当你使用Microsoft.Extensions.Http嵌套包中的东西时,你仍然需要通过using语句来引用它们。

    所以,这里没有任何问题。只需将using System.Net.Http; 添加到您的班级即可。

    【讨论】:

    • 我认为你错过了让事情变得更容易的Microsoft.Extensions.DependencyInjection
    【解决方案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;
                }
            }
    
        }
    
    }
    

    希望对你有所帮助

    【讨论】:

    • 我认为添加 Github 特定配置的代码应该是 class GitHubClient 的静态成员,而不是 Configure 中的匿名 lambda。只是imo。
    【解决方案3】:

    在你的 csproj 中添加这个包引用。

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

    【讨论】:

    • 这对我有帮助,虽然我需要更高的版本号&lt;PackageReference Include="Microsoft.AspNetCore.App" Version="3.1.3" /&gt;
    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2023-04-10
    • 1970-01-01
    • 2016-11-02
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多