是否可以将 HttpClient 配置为不保存 cookie?

Is it possible to configure HttpClient not to save cookies?

我有一个简单的 Asp.Net Core WebApi,我在其中使用 HttpClient 发送一些自定义 Web 请求。我像这样使用 HttpClient

services.AddHttpClient<IMyInterface, MyService>()
...

public class MyService : IMyInterface
{
    private readonly HttpClient _client;

    public MyService(HttpClient client)
    {
        _client = client;
    } 

    public async Task SendWebRequest()
    {
        var url = "https://MyCustomUrl.com/myCustomResource";
        var request = new HttpRequestMessage(HttpMethod.Get, url);
        var response = await _client.SendAsync(request);
        ...
    }
}   

我注意到当我发送多个请求时,HttpClient 会保存它在 Set-Cookie header 中通过第一个 响应 收到的 cookie。它将这些 cookie 添加到连续的 request headers。 (我已经用 fiddler 检查了这个)。流量:

//First requst
GET https://MyCustomUrl.com/myCustomResource HTTP/1.1

//First response
HTTP/1.1 200 OK
Set-Cookie: key=value
...

//Second request
GET https://MyCustomUrl.com/myCustomResource HTTP/1.1
Cookie: key=value

//Second response
HTTP/1.1 200 OK
...

有没有办法强制HttpClient不添加cookies?

这只发生在同一个 session 中,所以如果我要处理 HttpClient,则不会添加 cookie。但是处理 HttpClient 可能会带来一些其他问题。

参见 HttpClientHandler.UseCookies

Gets or sets a value that indicates whether the handler uses the CookieContainer property to store server cookies and uses these cookies when sending requests.

所以你需要做:

var handler = new HttpClientHandler() { UseCookies = false };
var httpClient = new HttpClient(handler);

如果您在 asp.net 核心中使用 HttpClientFactory,那么 建议这样做的方法是:

services.AddHttpClient("configured-inner-handler")
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { UseCookies = false });