1

我正在尝试使用Refit替换我不久前编写的现有 HttpClient 包装类。在大多数情况下,一切都运行良好,但有一种情况是我需要将 cookie 与我的请求一起传递。我想我的部分困惑是我不知道使用 HttpClientHandler CookieContainer 时 cookie 的确切位置。

这是我试图模仿的 cookie 设置代码:

var handler = new HttpClientHandler();
handler.CookieContainer = new CookieContainer();
handler.CookieContainer.SetCookies(new Uri(endPoint), cookieString);

var httpClient = new HttpClient(handler);
var response = await httpClient.PutAsync(endPoint, jsonContent);

当我单步执行此代码时,我没有看到将 cookie 放置在标头中,并且我很难在请求或响应标头/值/等的任何地方看到它。

我应该如何用改装来模仿这个?我已经尝试将它放在标题中(这有效,它进入标题)但这不是 CookieContainer 似乎做的,所以它不起作用。

4

1 回答 1

1

基本上你会这样做。

RestService.For<T>()有一个采用 preconfigured 的覆盖HttpClient,因此您使用HttpClientHandler具有 cookie 容器的 初始化它。

这是一个例子:

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Refit;

class Program
{
    static async Task Main(string[] args)
    {
        // Your base address is the same for cookies and requests
        var baseAddress = new Uri("https://httpbin.org");

        // Set your cookies up in the cookie container of an HttpClientHandler
        var handler = new HttpClientHandler();
        handler.CookieContainer.Add(baseAddress, new Cookie("C", "is for cookie"));

        // Use that to create a new HttpClient with the same base address
        var client = new HttpClient(handler) { BaseAddress = baseAddress };

        // Pass that client to `RestService.For<T>()`
        var httpBin = RestService.For<IHttpBinApi>(client);

        var response = await httpBin.GetHeaders();

        Console.WriteLine(response);
    }
}

public interface IHttpBinApi
{
    // This httpbin API will echo the request headers back at us
    [Get("/headers")]
    Task<string> GetHeaders();
}

上面的输出是:

{
  "headers": {
    "Cookie": "C=is for cookie",
    "Host": "httpbin.org"
  }
}
于 2019-06-17T01:37:56.870 回答