gpt4 book ai didi

c# - 带有类型化客户端的 cookieContainer

转载 作者:行者123 更新时间:2023-12-04 14:18:29 28 4
gpt4 key购买 nike

需要向需要特定 cookie 的服务器发出请求。能够使用带有 cookiecontainer 的 HTTP 客户端和处理程序来做到这一点。通过使用 Typed 客户端,无法找到设置 cookiecontainer 的方法。

使用 httpclient:

var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (HttpClient client = new HttpClient(handler))
{
//.....

// Used below method to add cookies
AddCookies(cookieContainer);

var response = client.GetAsync('/').Result;
}

使用 HttpClientFactory:

在启动.cs
services.AddHttpClient<TypedClient>().
ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
CookieContainer = new CookieContainer()
});

在 Controller 类中
// Need to call AddCookie method here
var response =_typedclient.client.GetAsync('/').Result;

在 Addcookie 方法中,我需要将 cookie 添加到容器中。任何建议如何做到这一点。

最佳答案

创建抽象以提供对 CookieContainer 实例的访问。

例如

public interface ICookieContainerAccessor {
CookieContainer CookieContainer { get; }
}

public class DefaultCookieContainerAccessor : ICookieContainerAccessor {
private static Lazy<CookieContainer> container = new Lazy<CookieContainer>();
public CookieContainer CookieContainer => container.Value;
}

在启动期间将 cookie 容器添加到服务集合并使用它来配置主要的 HTTP 消息处理程序

启动.配置服务
//create cookie container separately            
//and register it as a singleton to be accesed later
services.AddSingleton<ICookieContainerAccessor, DefaultCookieContainerAccessor>();

services.AddHttpClient<TypedClient>()
.ConfigurePrimaryHttpMessageHandler(sp =>
new HttpClientHandler {
//pass the container to the handler
CookieContainer = sp.GetRequiredService<ICookieContainerAccessor>().CookieContainer
}
);

最后,在需要的地方注入(inject)抽象

例如
public class MyClass{
private readonly ICookieContainerAccessor accessor;
private readonly TypedClient typedClient;

public MyClass(TypedClient typedClient, ICookieContainerAccessor accessor) {
this.accessor = accessor;
this.typedClient = typedClient;
}

public async Task SomeMethodAsync() {
// Need to call AddCookie method here
var cookieContainer = accessor.CookieContainer;
AddCookies(cookieContainer);

var response = await typedclient.client.GetAsync('/');

//...
}

//...
}

关于c# - 带有类型化客户端的 cookieContainer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643742/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com