public void CookieHeaderValue_TryParse_AcceptsValidValues(CookieHeaderValue cookie, string expectedValue) { Assert.True(CookieHeaderValue.TryParse(expectedValue, out var header)); Assert.Equal(cookie, header); Assert.Equal(expectedValue, header !.ToString()); }
private void EnsureCookie(HttpResponseHeaders headers) { if (headers == null) { return; } if (!headers.TryGetValues("Set-Cookie", out var tmpList)) { return; } var cookieList = tmpList.ToList(); // var cookieList = response.Headers.GetValues("Set-Cookie").ToList(); if (cookieList != null && cookieList.Count > 0) { #if NETSTANDARD // Get the first cookie this.Cookie = CookieHeaderValue.ParseList(cookieList).FirstOrDefault(); #else //try to parse the very first cookie if (CookieHeaderValue.TryParse(cookieList[0], out var cookie)) { this.Cookie = cookie; } #endif } }
public override void Render(TextWriter writer) { string url = this.Url; if (string.IsNullOrWhiteSpace(url)) { return; } string cookie = null; var context = HttpContext.Current; if (context != null) { cookie = context.Request.Headers["Cookie"]; } var webClient = new WebClient(); webClient.Headers.Add("X-REQUESTED-WITH", "Remote-CMS, Sitecore"); if (cookie != null) { if (global::Sitecore.Context.PageMode.IsNormal) { webClient.Headers.Add(HttpRequestHeader.Cookie, cookie); } else { CookieHeaderValue cookieHeader; if (CookieHeaderValue.TryParse(cookie, out cookieHeader)) { //remove analytics and session cookie, httphandler of mvc/sitecore has IRequireSessionState, leading to a deadlock on the sessionstate: //http://stackoverflow.com/questions/2526168/asp-net-ihttpasynchandler-and-irequiressessionstate-not-working var sessionCookieName = GetSessionIdCookieName(); var analyticscookies = cookieHeader.Cookies.Where(c => c.Name == sessionCookieName || c.Name.StartsWith("SC_ANALYTICS_GLOBAL_COOKIE")).ToArray(); foreach (var c in analyticscookies) { cookieHeader.Cookies.Remove(c); } webClient.Headers.Add(HttpRequestHeader.Cookie, cookieHeader.ToString()); } else { webClient.Headers.Add(HttpRequestHeader.Cookie, cookie); } } } var result = webClient.DownloadString(url); if (string.IsNullOrWhiteSpace(result)) { return; } writer.Write(result); }
public static IEnumerable <CookieState> GetCookies(this HttpResponseMessage resp) { if (resp.Headers.TryGetValues("Set-Cookie", out var values)) { var cookies = new List <CookieState>(); foreach (var value in values) { if (CookieHeaderValue.TryParse(value, out var cookie) && (cookie.Expires == null || cookie.Expires > DateTime.Now)) { cookies.AddRange(cookie.Cookies); } } return(cookies); } return(Enumerable.Empty <CookieState>()); }
public static IEnumerable <CookieState> GetCookies(this HttpResponseMessage resp) { IEnumerable <string> values; if (resp.Headers.TryGetValues("Set-Cookie", out values)) { var cookies = new List <CookieState>(); foreach (var value in values) { CookieHeaderValue cookie; if (CookieHeaderValue.TryParse(value, out cookie)) { cookies.AddRange(cookie.Cookies); } } return(cookies); } return(Enumerable.Empty <CookieState>()); }
private IEnumerable <CookieHeaderValue> responseCookies() { var result = new List <CookieHeaderValue>(); IEnumerable <string> cookieHeaders; if (_response.Headers.TryGetValues("Cookie", out cookieHeaders)) { cookieHeaders.Each(header => { CookieHeaderValue cookieHeaderValue; if (CookieHeaderValue.TryParse(header, out cookieHeaderValue)) { result.Add(cookieHeaderValue); } }); } return(result); }
public void AddCookies_AddsCookies(string expectedCookie) { // Arrange HttpResponseHeaders headers = CreateHttpResponseHeaders(); List <CookieHeaderValue> cookies = new List <CookieHeaderValue>(); CookieHeaderValue cookie; bool parsedCorrectly = CookieHeaderValue.TryParse(expectedCookie, out cookie); cookies.Add(cookie); // Act headers.AddCookies(cookies); // Assert Assert.True(parsedCorrectly); IEnumerable <string> actualCookies; bool addedCorrectly = headers.TryGetValues("Set-Cookie", out actualCookies); Assert.True(addedCorrectly); Assert.Equal(1, actualCookies.Count()); Assert.Equal(expectedCookie, actualCookies.ElementAt(0)); }
/// <summary>Gets any cookie headers present in the request.</summary> /// <returns>A collection of <see cref="T:System.Net.Http.Headers.CookieHeaderValue" /> instances.</returns> /// <param name="headers">The request headers.</param> public static Collection <CookieHeaderValue> GetCookies(this HttpRequestHeaders headers) { if (headers == null) { throw Error.ArgumentNull("headers"); } Collection <CookieHeaderValue> collection = new Collection <CookieHeaderValue>(); IEnumerable <string> enumerable; if (headers.TryGetValues("Cookie", out enumerable)) { foreach (string current in enumerable) { CookieHeaderValue item; if (CookieHeaderValue.TryParse(current, out item)) { collection.Add(item); } } } return(collection); }
/// <summary> /// Gets any cookie headers present in the request. Each <c>Cookie</c> header is /// represented as one <see cref="CookieHeaderValue"/> instance. A <see cref="CookieHeaderValue"/> /// contains information about the domain, path, and other cookie information as well as one or /// more <see cref="CookieState"/> instances. Each <see cref="CookieState"/> instance contains /// a cookie name and whatever cookie state is associate with that name. The state is in the form of a /// <see cref="System.Collections.Specialized.NameValueCollection"/> which on the wire is encoded as HTML Form URL-encoded data. /// This representation allows for multiple related "cookies" to be carried within the same /// <c>Cookie</c> header while still providing separation between each cookie state. A sample /// <c>Cookie</c> header is shown below. In this example, there are two <see cref="CookieState"/> /// with names <c>stateA</c> and <c>stateB</c> respectively. Further, each cookie state contains two name/value /// pairs (name1/value1 and name2/value2) and (name3/value3 and name4/value4). /// <code> /// Cookie: stateA=name1=value1&name2=value2; stateB=name3=value3&name4=value4; domain=domain1; path=path1; /// </code> /// </summary> /// <param name="headers">The request headers</param> /// <returns>A collection of <see cref="CookieHeaderValue"/> instances.</returns> public static Collection <CookieHeaderValue> GetCookies(this HttpRequestHeaders headers) { if (headers == null) { throw Error.ArgumentNull("headers"); } Collection <CookieHeaderValue> result = new Collection <CookieHeaderValue>(); IEnumerable <string> cookieHeaders; if (headers.TryGetValues(Cookie, out cookieHeaders)) { foreach (string cookieHeader in cookieHeaders) { CookieHeaderValue cookieHeaderValue; if (CookieHeaderValue.TryParse(cookieHeader, out cookieHeaderValue)) { result.Add(cookieHeaderValue); } } } return(result); }
public static string Cookie(this HttpRequestMessage request, string name) { string selectedCookieValue = null; var result = new Collection <CookieHeaderValue>(); IEnumerable <string> cookies; if (request.Headers.TryGetValues("Cookie", out cookies)) { foreach (string cookie in cookies) { CookieHeaderValue cookieHeaderValue; if (CookieHeaderValue.TryParse(cookie, out cookieHeaderValue)) { selectedCookieValue = cookieHeaderValue[name].Value; if (!string.IsNullOrEmpty(selectedCookieValue)) { break; } } } } return(selectedCookieValue); }
/// <summary> /// Process a request message with HttpClient object. /// </summary> public async Task <T> ProcessRequest <T>(T content, SerializationFormat serializationFormat, CancellationToken cancellationToken) { if (this.BaseUri == null) { throw new ArgumentException("BaseUri is not defined"); } HttpResponseMessage response = null; T responseMessage = default(T); try { if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } var requestUri = new StringBuilder(); requestUri.Append(this.BaseUri.ToString()); requestUri.Append(this.BaseUri.ToString().EndsWith("/", StringComparison.CurrentCultureIgnoreCase) ? string.Empty : "/"); // Add params if any if (ScopeParameters != null && ScopeParameters.Count > 0) { string prefix = "?"; foreach (var kvp in ScopeParameters) { requestUri.AppendFormat("{0}{1}={2}", prefix, Uri.EscapeUriString(kvp.Key), Uri.EscapeUriString(kvp.Value)); if (prefix.Equals("?")) { prefix = "&"; } } } // default handler if no one specified HttpClientHandler httpClientHandler = this.Handler ?? new HttpClientHandler(); // serialize dmSet content to bytearraycontent var serializer = BaseConverter <T> .GetConverter(serializationFormat); var binaryData = serializer.Serialize(content); ByteArrayContent arrayContent = new ByteArrayContent(binaryData); // do not dispose HttpClient for performance issue if (client == null) { client = new HttpClient(httpClientHandler); } // add it to the default header if (this.Cookie != null) { client.DefaultRequestHeaders.Add("Cookie", this.Cookie.ToString()); } HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri.ToString()) { Content = arrayContent }; // Adding the serialization format used requestMessage.Headers.Add("dotmim-sync-serialization-format", serializationFormat.ToString()); // Adding others headers if (this.CustomHeaders != null && this.CustomHeaders.Count > 0) { foreach (var kvp in this.CustomHeaders) { requestMessage.Headers.Add(kvp.Key, kvp.Value); } } //request.AddHeader("content-type", "application/json"); if (serializationFormat == SerializationFormat.Json && !requestMessage.Content.Headers.Contains("content-type")) { requestMessage.Content.Headers.Add("content-type", "application/json"); } response = await client.SendAsync(requestMessage, cancellationToken); if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } // get response from server if (!response.IsSuccessStatusCode) { throw new Exception(response.ReasonPhrase); } // try to set the cookie for http session var headers = response?.Headers; if (headers != null) { if (headers.TryGetValues("Set-Cookie", out IEnumerable <string> tmpList)) { var cookieList = tmpList.ToList(); // var cookieList = response.Headers.GetValues("Set-Cookie").ToList(); if (cookieList != null && cookieList.Count > 0) { #if NETSTANDARD // Get the first cookie this.Cookie = CookieHeaderValue.ParseList(cookieList).FirstOrDefault(); #else //try to parse the very first cookie if (CookieHeaderValue.TryParse(cookieList[0], out var cookie)) { this.Cookie = cookie; } #endif } } } using (var streamResponse = await response.Content.ReadAsStreamAsync()) if (streamResponse.CanRead && streamResponse.Length > 0) { responseMessage = serializer.Deserialize(streamResponse); } return(responseMessage); } catch (TaskCanceledException ex) { throw ex; } catch (Exception e) { if (response == null || response.Content == null) { throw e; } try { var exrror = await response.Content.ReadAsStringAsync(); WebSyncException webSyncException = JsonConvert.DeserializeObject <WebSyncException>(exrror); if (webSyncException != null) { throw webSyncException; } } catch (WebSyncException) { throw; } catch (Exception) { throw; } throw e; } }
public void CookieHeaderValue_TryParse_RejectsInvalidValues(string value) { Assert.False(CookieHeaderValue.TryParse(value, out var _)); }
/// <summary> /// Process a request message with HttpClient object. /// </summary> public async Task <U> ProcessRequestAsync <U>(HttpClient client, string baseUri, byte[] data, HttpStep step, Guid sessionId, ISerializerFactory serializerFactory, IConverter converter, int batchSize, CancellationToken cancellationToken) { if (client is null) { throw new ArgumentNullException(nameof(client)); } if (baseUri == null) { throw new ArgumentException("BaseUri is not defined"); } HttpResponseMessage response = null; var responseMessage = default(U); try { if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } // Get response serializer var responseSerializer = serializerFactory.GetSerializer <U>(); var requestUri = new StringBuilder(); requestUri.Append(baseUri); requestUri.Append(baseUri.EndsWith("/", StringComparison.CurrentCultureIgnoreCase) ? string.Empty : "/"); // Add params if any if (ScopeParameters != null && ScopeParameters.Count > 0) { string prefix = "?"; foreach (var kvp in ScopeParameters) { requestUri.AppendFormat("{0}{1}={2}", prefix, Uri.EscapeUriString(kvp.Key), Uri.EscapeUriString(kvp.Value)); if (prefix.Equals("?")) { prefix = "&"; } } } // get byte array content var arrayContent = data == null ? new ByteArrayContent(new byte[] { }) : new ByteArrayContent(data); // reinit client client.DefaultRequestHeaders.Clear(); // add it to the default header //if (this.Cookie != null) // client.DefaultRequestHeaders.Add("Cookie", this.Cookie.ToString()); // Create the request message var requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri.ToString()) { Content = arrayContent }; // Adding the serialization format used and session id requestMessage.Headers.Add("dotmim-sync-session-id", sessionId.ToString()); requestMessage.Headers.Add("dotmim-sync-step", ((int)step).ToString()); // serialize the serialization format and the batchsize we want. var ser = JsonConvert.SerializeObject(new { f = serializerFactory.Key, s = batchSize }); requestMessage.Headers.Add("dotmim-sync-serialization-format", ser); // if client specifies a converter, add it as header if (converter != null) { requestMessage.Headers.Add("dotmim-sync-converter", converter.Key); } // Adding others headers if (this.CustomHeaders != null && this.CustomHeaders.Count > 0) { foreach (var kvp in this.CustomHeaders) { if (!requestMessage.Headers.Contains(kvp.Key)) { requestMessage.Headers.Add(kvp.Key, kvp.Value); } } } // If Json, specify header if (serializerFactory.Key == SerializersCollection.JsonSerializer.Key && !requestMessage.Content.Headers.Contains("content-type")) { requestMessage.Content.Headers.Add("content-type", "application/json"); } // Eventually, send the request response = await client.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } // throw exception if response is not successfull // get response from server if (!response.IsSuccessStatusCode && response.Content != null) { await HandleSyncError(response, serializerFactory); } // try to set the cookie for http session var headers = response?.Headers; if (headers != null) { if (headers.TryGetValues("Set-Cookie", out var tmpList)) { var cookieList = tmpList.ToList(); // var cookieList = response.Headers.GetValues("Set-Cookie").ToList(); if (cookieList != null && cookieList.Count > 0) { #if NETSTANDARD // Get the first cookie this.Cookie = CookieHeaderValue.ParseList(cookieList).FirstOrDefault(); #else //try to parse the very first cookie if (CookieHeaderValue.TryParse(cookieList[0], out var cookie)) { this.Cookie = cookie; } #endif } } } if (response.Content == null) { throw new HttpEmptyResponseContentException(); } using (var streamResponse = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) if (streamResponse.CanRead && streamResponse.Length > 0) { responseMessage = responseSerializer.Deserialize(streamResponse); } return(responseMessage); } catch (SyncException) { throw; } catch (Exception e) { if (response == null || response.Content == null) { throw new HttpResponseContentException(e.Message); } var exrror = await response.Content.ReadAsStringAsync().ConfigureAwait(false); throw new HttpResponseContentException(exrror); } }