我有一个简单的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
会将第一个响应中接收到的 cookies 存储在 Set-Cookie
头中,并将这些 cookies 添加到后续请求的头部。 (我用 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?
这只会在同一会话中发生,因此如果我丢弃 HttpClient
,则不会添加 cookies。但丢弃 HttpClient
可能会带来其他问题。
HttpClient
实例,因为这是不好的做法。如果手动创建并且可以处理它,那么所有的cookies都将被丢弃。 - Ramūnas