需要向需要特定cookie的服务器发出请求。可以使用HTTP客户端和带有cookiecontainer的处理程序来执行此操作。通过使用类型化客户端,无法找到设置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:
在startup.cs
services.AddHttpClient<TypedClient>().
ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
CookieContainer = new CookieContainer()
});
在控制器类中
// Need to call AddCookie method here
var response =_typedclient.client.GetAsync('/').Result;
在Addcookie方法中,我需要将cookie添加到容器中。有关如何执行此操作的任何建议。
答案 0 :(得分:0)
创建抽象以提供对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消息处理程序
Startup.ConfigureServices
//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
}
);
最后,在需要的地方注入抽象
例如
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('/');
//...
}
//...
}