Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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