Skip to content

Instantly share code, notes, and snippets.

@stefanhendriks
Last active June 4, 2023 17:14
Show Gist options
  • Save stefanhendriks/791391f10a40bde160568cf5ca79cc53 to your computer and use it in GitHub Desktop.
Save stefanhendriks/791391f10a40bde160568cf5ca79cc53 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));
}
}
@sandorfr
Copy link

Yes @rpendleton you are right this leads to a formatting where the semicolon is missing.

@bhargavPP
Copy link

based on your mplmentation we tries but when we get httpresponse it s header doesnt contain set-cookie value.is there anhting that i have to apart from this?

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