C# 具有类型化客户端的cookieContainer
需要向需要特定cookie的服务器发出请求。能够通过cookiecontainer使用HTTP客户端和处理程序实现这一点。通过使用类型化客户端,无法找到设置cookiecontainer的方法 使用httpclient:C# 具有类型化客户端的cookieContainer,c#,.net-core,dotnet-httpclient,cookiecontainer,httpclientfactory,C#,.net Core,Dotnet Httpclient,Cookiecontainer,Httpclientfactory,需要向需要特定cookie的服务器发出请求。能够通过cookiecontainer使用HTTP客户端和处理程序实现这一点。通过使用类型化客户端,无法找到设置cookiecontainer的方法 使用httpclient: var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer }) using (Htt
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()
});
在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;
}
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('/');
//...
}
//...
}
是否有办法清除以前请求的cookie或为每个请求获取新的CookieContainer?
//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('/');
//...
}
//...
}