标签: httpclientfactory

如何编写单元测试用例IHttpClientFactory

我在服务层有一个方法来连接到服务,并且我正在使用IHttpClientFactory. 我的方法运行良好。现在我正在尝试为此编写单元测试用例。

public async Task<MyObject> MyMethodAsync(string arg1, string arg2)
{
    var client = _httpClientFactory.CreateClient("XYZ");

    var Authkey = "abc"; 
    var AuthToken = "def";
       
    var headers = new Dictionary<string, string>
        {
            { Authkey,AuthToken }
        };

    client.AddTokenToHeader(headers); //This method set  the DefaultRequestheader from the dictionary object

    var reqData = new
    {
        prop1 = "X", 
        prop2 = "Y"
    };//req object

    var content = new StringContent(JsonConvert.SerializeObject(reqData), Encoding.UTF8, "application/json");

    //This is httpClient Post call for posting data 
    HttpResponseMessage response = await client.PostAsync("postData", content); 
    if …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing dotnet-httpclient asp.net-core httpclientfactory

6
推荐指数
1
解决办法
9492
查看次数

如何使用 HttpClientFactory 为命名的 HttpClient 定义 HttpClientHandler

旧代码:

Client = new HttpClient(new HttpClientHandler() { DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials });

// set an default user agent string, some services does not allow emtpy user agents
if (!Client.DefaultRequestHeaders.Contains("User-Agent"))
    Client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0");
Run Code Online (Sandbox Code Playgroud)

尝试使用新的 ASP.NET Core 2.1 HttpClientFactory 实现相同的功能:

services.AddHttpClient("Default", client =>
        {
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
        }).ConfigurePrimaryHttpMessageHandler(handler => new HttpClientHandler() { DefaultProxyCredentials = CredentialCache.DefaultNetworkCredentials });          
Run Code Online (Sandbox Code Playgroud)

不幸的是,我收到一个 HTTP 407(代理身份验证)错误。我做错了什么?

asp.net dotnet-httpclient .net-core asp.net-core httpclientfactory

5
推荐指数
1
解决办法
6118
查看次数

ASP.NET Core 2从HttpResponseMessage获取Cookie

目前,我正在使用ASP.NET Core 2编写一个项目,并且正在尝试从第三方网站获取JSON文件。问题在于该网站需要一些Cookie才能从中检索数据。我在Startup.cs文件中实现了一个键入的HttpClient,如下所示:

    services.AddHttpClient<IMyClient, MyClient>().ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler()
        {
            UseCookies = true,
            UseDefaultCredentials = true,
            CookieContainer = new CookieContainer()
        };
    });
Run Code Online (Sandbox Code Playgroud)

有什么方法可以访问CookieContainer来使用CookieContainer.GetCookies()方法,以便可以从HttpResponseMessage复制各种Cookie,例如会话Cookie和一些验证令牌?

抱歉,如果我做错了,这是我的第一篇文章。

编辑

通过在请求管道中添加HttpMessageHandler使其工作

services.AddHttpClient<IMyHttpClient, MyHttpClient>()
                    .AddHttpMessageHandler<MyMessageHandler>();
Run Code Online (Sandbox Code Playgroud)

并在HttpMessageHandler中编辑http标头信息

public class MyMessageHandler : DelegatingHandler
{
    private readonly CookieContainer _cookies;

    public MyMessageHandler()
    {
        _cookies = new CookieContainer();
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken cancellationToken)
    {
        try
        {
            if (_cookies.Count == 0 && message.RequestUri.Host.Contains("example.com"))
            {
                // Simulate the Request
                var getCookieMesssage = new HttpRequestMessage()
                {
                    RequestUri = new …
Run Code Online (Sandbox Code Playgroud)

c# cookies dotnet-httpclient asp.net-core-2.1 httpclientfactory

5
推荐指数
1
解决办法
1628
查看次数

如何为直接通过HttpClientFactory创建的HttpClient配置Web代理?

  • 直接地,我的意思是没有Asp.Net Core IoC / DI帮助程序。

我没有找到有关它的文档,我认为我当前的解决方案不是最佳的,因为处理程序生命周期不是由HttpClientFactory管理的:

var proxiedHttpClientHandler = new HttpClientHandler() { Proxy = httpProxy };
_createHttpClient = () => HttpClientFactory.Create(proxiedHttpClientHandler);
Run Code Online (Sandbox Code Playgroud)

有更好的解决方案吗?

.net c# dotnet-httpclient .net-core httpclientfactory

5
推荐指数
2
解决办法
3655
查看次数

具有动态配置的 HttpClientFactory

我正在开发 .net core web 应用程序,它需要以特定的时间间隔(每 2 分钟,20 次不同的 API 调用,我需要向最终用户显示 API 结果)调用远程 API ,托管有4 个不同的域名

我使用 HttpClient 来调用远程 API。但是随着用户的增加,我的 CPU 使用率增加了 40%。我怀疑 HttpClient 可能是原因。在浏览了几篇博客之后,我正在尝试使用 HttpClientFactory。
我有一个从 Controller Action 调用的方法,我需要根据几个参数动态识别 BaseUrl。目前我在 StartUp.cs 中创建了 4 个 NamedClients,如下所示:

   services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl1, client =>
       {
           client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl1").Value);
           client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
           client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
           var userAgent = "C# app";
           client.DefaultRequestHeaders.Add("User-Agent", userAgent);
       }).SetHandlerLifetime(TimeSpan.FromMinutes(5));
        services.AddHttpClient(ApiConfig.NamedHttpClients.TestUrl2, client =>
        {
            client.BaseAddress = new Uri(Configuration.GetSection("BaseUrls").GetSection("TestUrl2").Value);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("Authorization", "Basic " + ApiConfig.GetEncodedCredentials(Configuration));
            var userAgent …
Run Code Online (Sandbox Code Playgroud)

asp.net-core-2.1 httpclientfactory .net-core-2.1

5
推荐指数
0
解决办法
880
查看次数

如何显式地将 httpclienthandler 传递给 httpclientfactory ?

我想过使用 HttpClientFactory 但我需要在拨打电话时附加证书目前,我正在使用 HttpClient,但不知道如何附加证书。
下面是httpClient代码:

HttpClientHandler httpClientHandler = new HttpClientHandler
{
    SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12,
    ClientCertificateOptions = ClientCertificateOption.Manual
};
httpClientHandler.ClientCertificates.Add(CertHelper.GetCertFromStoreByThumbPrint(_Settings.MtlsThumbPrint, StoreName.My, _Settings.IgnoreCertValidChecking));

httpClientHandler.ServerCertificateCustomValidationCallback = OnServerCertificateValidation;

HttpClient _client = new HttpClient(httpClientHandler)
{
    Timeout = TimeSpan.FromMinutes(1),
    BaseAddress = new Uri(_Settings.BaseUrl)
};
Run Code Online (Sandbox Code Playgroud)

那么,如何将上面的httpClient转换为HttpClientFactory呢?

任何帮助,将不胜感激。

c# .net-core httpclientfactory

5
推荐指数
1
解决办法
4335
查看次数

AddHttpClient 配置的 HttpClient.Timeout 被忽略

当使用推荐的AddHttpClient扩展来配置IHttpClientFactory并包含一些默认HttpClient设置时,我为该属性设置的值在我随后创建的实例Timeout中看不到。HttpClient

演示使用 Azure Function,类似于 ASP.NET Core。

public class Startup : FunctionsStartup
{
    public static readonly int PushTimeoutMs = 3000;

    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddHttpClient("PushNotification", client =>
        {
            client.Timeout = TimeSpan.FromMilliseconds(PushTimeoutMs);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

创建客户端。

public class TestFunctionTwo
{
    public TestFunctionTwo(IHttpClientFactory httpClientFactory)
    {
        this.HttpClientFactory = httpClientFactory;
    }

    //

    public IHttpClientFactory HttpClientFactory { get; }

    //

    [FunctionName("TestFunctionTwo")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log) …
Run Code Online (Sandbox Code Playgroud)

.net-core httpclientfactory

5
推荐指数
1
解决办法
1万
查看次数

来自 IHttpClientFactory 的类型化 HttpClient 实例的生命周期是多少,其中将接收该实例的类型注册为“AddScoped”?

长话短说

在.NET 6 中:

接收该HttpClient实例的类型被注册为“Scoped”的类型化实例的生命周期是多少?IHttpClientFactory

当我们像下面的摘录那样注册它时,它不应该是一种“定时单例”(无论使用它的类的生命周期如何)吗?或者是HttpClient Transient - 并且 .NET 不缓存其任何配置,并且仅池化处理程序?

services.AddHttpClient<IServiceInterface, ServiceImpl>(client =>
{
    client.BaseAddress = "<some absolute URL here>";
}
    .SetHandlerLifetime(TimeSpan.FromMinutes(5));

services.AddScoped<IServiceInterface, ServiceImpl>();
Run Code Online (Sandbox Code Playgroud)

语境

我正在开发的应用程序访问不同地址的多个外部 API。我将每个服务访问逻辑封装到具有各自接口的服务类中,以便可以在运行时注入它们。按照 Microsoft 的规定,我使用的是 Typed HttpClients,并且我编写了一个辅助方法来配置它们Startup.cs

public static IServiceCollection ConfigureHttpClientForService<TInterface, TImpl>
    (this IServiceCollection services, Func<IServiceProvider, Uri> func)
    where TInterface : class
    where TImpl : class, TInterface
{
    services.AddHttpClient<TInterface, TImpl>((provider, client) =>
    {
        var uri = func(provider);
        client.BaseAddress = uri;
    })
        // Polly Rules here and other …
Run Code Online (Sandbox Code Playgroud)

.net c# dependency-injection dotnet-httpclient httpclientfactory

5
推荐指数
1
解决办法
1769
查看次数

.NET Framework 4.7.2 中的 IHttpClientFactory 无需依赖注入

我计划在我的 ASP.NET Framework 4.7.2 Webforms 项目中使用 Microsoft.Extensions.Http 包。由于 .NET Framework 中没有内置 DI 容器,因此我没有使用 DI 包。根据这个答案,我不确定最后一行 -

Microsoft.Extensions.Http 仅提供 HttpClientFactory,而不提供新的优化的 HttpClient。这仅在 .NET Core 2.1 中可用

我可以在我的框架项目中实现没有 DI 并使用单例方法的 IHttpClientFactory 并摆脱直接使用 HttpClient 的 2 个问题 - 套接字耗尽和 DNS 解析吗?根据上述评论还有其他需要做的事情吗

.net dependency-injection webforms httpclientfactory

5
推荐指数
1
解决办法
3273
查看次数

如何使用 IHttpClientFactory 在 Blazor 服务器中配置 HttpClient 基地址

我正在尝试HttpClient在使用的Blazor服务器中配置的基地址,IHttpClientFactory但出现运行时异常:

    services.AddHttpClient("ApiClient", (provider, client) =>
    {
        var uriHelper = provider.GetRequiredService<NavigationManager>();
        client.BaseAddress = new Uri(uriHelper.BaseUri);
    });
Run Code Online (Sandbox Code Playgroud)
System.InvalidOperationException: 'Cannot resolve scoped service 'Microsoft.AspNetCore.Components.NavigationManager' from root provider.'
Run Code Online (Sandbox Code Playgroud)

异常截图

有谁知道这里可能是什么问题?

dotnet-httpclient .net-core blazor httpclientfactory blazor-server-side

4
推荐指数
1
解决办法
2787
查看次数