1

I'm trying to use Refit to replace an existing HttpClient wrapper class that I wrote a while back. Things are working pretty well in most cases, but there is one case where I need to pass a cookie along with my request. Part of my confusion I suppose is that I don't know where exactly a cookie goes when using the HttpClientHandler CookieContainer.

This is the cookie setting code I am trying to mimic:

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);

When I step through this code I don't see the cookie being placed in the header, and I struggle to see it anywhere on the request or response headers/values/etc.

How should I mimic this with Refit? I've tried placing it in the header (which works, it goes into the header) but that's not what the CookieContainer seems to do, so it's not working.

Hoser
  • 4,974
  • 9
  • 45
  • 66

1 Answers1

1

Essentially you'd do it the same way.

RestService.For<T>() has an override that takes a preconfigured HttpClient, so you initialize that with the HttpClientHandler that has your cookie container.

Here's an example:

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();
}

The output of the above is:

{
  "headers": {
    "Cookie": "C=is for cookie",
    "Host": "httpbin.org"
  }
}
Bennor McCarthy
  • 11,415
  • 1
  • 49
  • 51
  • In the same way you can get the cookies from a Post, for example. The difference would be that instead of adding to CookieContainer, after the call, the cookies could be retrieved from `handler.CookieContainer.GetCookies(baseAddress).Cast()` – tridy Sep 04 '19 at 13:03