【问题标题】:Simple way to transfer cookies from current HttpContext into new created HttpClient request将 cookie 从当前 HttpContext 传输到新创建的 HttpClient 请求的简单方法
【发布时间】:2020-12-10 03:55:34
【问题描述】:

我正在尝试包装一些 api 请求

[Route("foo")]
public Task Foo()
{
    using var http = new HttpClient();
    return http.PostAsync(
                  Endpoint,
                  new FormUrlEncodedContent(new Dictionary<string, string>
                  {
                      { ClientId, "ClientId" },
                  }),
                  CancellationToken.None)
            .ConfigureAwait(false);
}

并遇到问题。原因在于被调用端点使用的 cookie。

有什么方法可以将 cookie 从我当前的 HttpContex 转移到 HttpClient Post call?我知道,我可以使用CookieContainerHttpClientHandler 并将所有这些东西传递给HttpClient,但我想使用更优雅的东西。

【问题讨论】:

  • AddHeaderPropagation middleware 够优雅吗?
  • @PeterCsala 绰绰有余,只需要迁移到核心 3.1

标签: c# .net asp.net-web-api cookies dotnet-httpclient


【解决方案1】:

只需从传入请求中获取Cookie 标头并添加到传出请求中即可。为单个请求设置标头将需要显式创建 HttpRequestMessage 并使用 HttpClient.SendAsync 发送它,但这相当简单:

var outgoing = new HttpRequestMessage(HttpMethod.Post, uri);
outgoing.Content = new FormUrlEncodedContent(...);
if (Request.Headers.TryGetValue("Cookie", out var cookies))
{
    outgoing.Headers.TryAddWithoutValidation("Cookie", cookies);
}
await http.SendAsync(outgoing);

【讨论】:

  • 谢谢,但这与在概念上使用CookieContainer 有区别吗?
  • 是的,它有很大的不同。 CookieContainer 是一种高级抽象,用于以浏览器的方式模拟用户“会话”,它与 HttpClient/Handler 紧密耦合。所有你在你的问题中陈述的你想避免的。这是为单个请求直接转发 cookie 标头的简单方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
  • 2016-02-03
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多