我正在尝试使用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似乎不会这样做,所以它不起作用。
发布于 2019-06-17 09:37:57
从本质上讲,你会用同样的方法来做。
cookie有一个覆盖,它接受一个预先配置的HttpClient,所以您可以使用包含您的RestService.For<T>()容器的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"
}
}https://stackoverflow.com/questions/54777907
复制相似问题