【发布时间】:2024-05-01 16:20:01
【问题描述】:
我有一个简单的Asp.Net Core WebApi,我使用HttpClient 发送一些自定义网络请求。我像这样使用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 标头中保存它收到的第一个 response cookie。它将这些 cookie 添加到连续的 request 标头中。 (我已经用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 不添加cookie?
这只会发生在同一个会话中,所以如果我要处理 HttpClient 则不会添加 cookie。但是处理HttpClient 可能会带来一些其他问题。
【问题讨论】:
标签: c# asp.net-core cookies dotnet-httpclient