首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Refit模拟CookieContainer行为

使用Refit模拟CookieContainer行为
EN

Stack Overflow用户
提问于 2019-02-20 10:22:31
回答 1查看 569关注 0票数 1

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

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

代码语言:javascript
复制
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似乎不会这样做,所以它不起作用。

EN

回答 1

Stack Overflow用户

发布于 2019-06-17 09:37:57

从本质上讲,你会用同样的方法来做。

cookie有一个覆盖,它接受一个预先配置的HttpClient,所以您可以使用包含您的RestService.For<T>()容器的HttpClientHandler对其进行初始化。

下面是一个例子:

代码语言:javascript
复制
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();
}

上面的输出是:

代码语言:javascript
复制
{
  "headers": {
    "Cookie": "C=is for cookie",
    "Host": "httpbin.org"
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54777907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档