Created
June 11, 2016 15:00
-
-
Save akunzai/b996507c9766e95679cf403d63555e77 to your computer and use it in GitHub Desktop.
clone Cookies from Response to Request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
namespace System.Net.Http | |
{ | |
public static class HttpResponseExtensions | |
{ | |
/// <summary> | |
/// clone Cookies from Response to Request | |
/// </summary> | |
/// <param name="response"></param> | |
/// <param name="path"></param> | |
/// <param name="method"></param> | |
/// <returns></returns> | |
public static HttpRequestMessage GetRequest(this HttpResponseMessage response, string path, HttpMethod method = null) | |
{ | |
var request = new HttpRequestMessage(method ?? HttpMethod.Get, path); | |
IEnumerable<string> values; | |
if (response.Headers.TryGetValues("Set-Cookie", out values)) | |
{ | |
var cookies = new List<string>(); | |
foreach (var value in values) | |
{ | |
var nameValue = value.Split(';')[0]; | |
var parts = nameValue.Split('='); | |
if (string.IsNullOrWhiteSpace(parts[1])) continue; | |
cookies.Add(nameValue); | |
} | |
request.Headers.Add("Cookie", string.Join("; ", cookies.ToArray())); | |
} | |
return request; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment