目前我正在开发一个使用 ASP.NET Core 2 编写的项目,并且正在尝试从第三方网站获取 JSON 文件。问题是该网站需要一些 cookie 才能从中检索数据。我在我的 Startup.cs 文件中实现了一个类型化的 HttpClient,如下所示:
services.AddHttpClient<IMyClient, MyClient>().ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
UseCookies = true,
UseDefaultCredentials = true,
CookieContainer = new CookieContainer()
};
});
有什么方法可以访问 CookieContainer 以使用 CookieContainer.GetCookies() 方法,以便我可以从 HttpResponseMessage 复制各种 cookie,如 Session Cookie 和一些验证令牌?
对不起,如果我做错了什么,这是我的第一篇文章。
编辑
通过在请求管道中添加 HttpMessageHandler 使其工作
services.AddHttpClient<IMyHttpClient, MyHttpClient>()
.AddHttpMessageHandler<MyMessageHandler>();
并编辑HttpMessageHandler中的http头信息
public class MyMessageHandler : DelegatingHandler
{
private readonly CookieContainer _cookies;
public MyMessageHandler()
{
_cookies = new CookieContainer();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken cancellationToken)
{
try
{
if (_cookies.Count == 0 && message.RequestUri.Host.Contains("example.com"))
{
// Simulate the Request
var getCookieMesssage = new HttpRequestMessage()
{
RequestUri = new Uri("http://www.example.com/"),
Content = message.Content,
Method = HttpMethod.Get,
};
// Simulate User Agent
foreach(var agent in message.Headers.UserAgent)
{
getCookieMesssage.Headers.UserAgent.Add(agent);
}
var testResponse = await base.SendAsync(getCookieMesssage, cancellationToken);
if (testResponse.Headers.TryGetValues("Set-Cookie", out var newCookies))
{
foreach (var item in SetCookieHeaderValue.ParseList(newCookies.ToList()))
{
var uri = new Uri(message.RequestUri, item.Path.Value);
// Add parsed cookies to CookieContainer
_cookies.Add(uri, new Cookie(item.Name.Value, item.Value.Value, item.Path.Value));
}
}
// Add parsed cookies to the header of the HttpRequestMessage
message.Headers.Add("Cookie", _cookies.GetCookieHeader(message.RequestUri));
}
// get response
var response = await base.SendAsync(message, cancellationToken).ConfigureAwait(false);
return response;
}catch(Exception ex)
{
throw ex;
}
}
}
此方法从 Set-Cookie 标头中获取所有 cookie,并将其添加到请求的 Cookie 标头中。