小编ume*_*110的帖子

带有类型化客户端的 cookieContainer

需要向需要特定cookie的服务器发出请求。能够使用 HTTP 客户端和带有 cookiecontainer 的处理程序来完成此操作。通过使用类型化客户端,无法找到设置 cookiecontainer 的方法。

使用http客户端:

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;
} 
Run Code Online (Sandbox Code Playgroud)

使用 HttpClientFactory:

在startup.cs中

services.AddHttpClient<TypedClient>().
           ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
           {
               CookieContainer = new CookieContainer()
            });
Run Code Online (Sandbox Code Playgroud)

在控制器类中

// Need to call AddCookie method here
var response =_typedclient.client.GetAsync('/').Result;
Run Code Online (Sandbox Code Playgroud)

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

c# cookiecontainer dotnet-httpclient .net-core httpclientfactory

7
推荐指数
1
解决办法
936
查看次数