通过改装模仿CookieContainer行为

时间:2019-02-20 02:22:31

标签: .net cookiecontainer refit

我正在尝试使用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放置在标题中,并且很难在请求或响应标题/值/等的任何位置看到它。

我应该如何用Refit模仿它?我试过将它放在标题中(它起作用,它进入标题中),但这不是CookieContainer似乎要做的,因此不起作用。

1 个答案:

答案 0 :(得分:0)

基本上,您将以相同的方式进行操作。

RestService.For<T>()的替代项采用了预先配置的HttpClient,因此您可以使用具有Cookie容器的HttpClientHandler对其进行初始化。

这是一个例子:

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"
  }
}