Skip to content

Instantly share code, notes, and snippets.

@shiitake
Forked from stefanhendriks/cookieshelper.cs
Created April 22, 2021 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiitake/d78f5426f070e8151c339939497d1b28 to your computer and use it in GitHub Desktop.
Save shiitake/d78f5426f070e8151c339939497d1b28 to your computer and use it in GitHub Desktop.
A cookies helper class to easily read and set cookies on HttpRequest (Asp.Net Core)
public class CookiesHelper
{
// Inspired from:
// https://github.com/aspnet/Mvc/blob/538cd9c19121f8d3171cbfddd5d842cbb756df3e/test/Microsoft.AspNet.Mvc.FunctionalTests/TempDataTest.cs#L201-L202
public static IDictionary<string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
{
IDictionary<string, string> result = new Dictionary<string, string>();
IEnumerable<string> values;
if (response.Headers.TryGetValues("Set-Cookie", out values))
{
SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
{
result.Add(cookie.Name, cookie.Value);
});
}
return result;
}
public static HttpRequestMessage PutCookiesOnRequest(HttpRequestMessage request, IDictionary<string, string> cookies)
{
cookies.Keys.ToList().ForEach(key =>
{
request.Headers.Add("Cookie", new CookieHeaderValue(key, cookies[key]).ToString());
});
return request;
}
public static HttpRequestMessage CopyCookiesFromResponse(HttpRequestMessage request, HttpResponseMessage response)
{
return PutCookiesOnRequest(request, ExtractCookiesFromResponse(response));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment