Instantly share code, notes, and snippets.

Embed
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));
}
}
@rpendleton

This comment has been minimized.

Copy link

rpendleton commented Jan 29, 2019

According to RFC 6265, Section 5.4:

When the user agent generates an HTTP request, the user agent MUST NOT attach more than one Cookie header field.

As such, I believe this implementation isn't quite right since it will result in multiple Cookie headers being set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment