public void CookieHeaderValue_ParseList_ExcludesInvalidValues(IList <CookieHeaderValue> cookies, string[] input) { var results = CookieHeaderValue.ParseList(input); // ParseList always returns a list, even if empty. TryParseList may return null (via out). Assert.Equal(cookies ?? new List <CookieHeaderValue>(), results); }
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 } }
/// <summary> /// Gets cookies from the HTTP request. /// </summary> /// <param name="request">HTTP request from which the cookies are retrieved.</param> /// <returns> /// List of <see cref="CookieHeaderValue"/> objects. If the request does not have any cookies, empty list is returned. /// </returns> /// <remarks><para>This method is available only in .NET Core version of the library.</para></remarks> public static IList <CookieHeaderValue> GetCookies(this HttpRequestMessage request) { if (request.Headers.TryGetValues(HeaderNames.Cookie, out IEnumerable <string> values)) { return(CookieHeaderValue.ParseList(values.ToList())); } return(new List <CookieHeaderValue>()); }
/// <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_ParseList_AcceptsValidValues(IList <CookieHeaderValue> cookies, string[] input) { var results = CookieHeaderValue.ParseList(input); Assert.Equal(cookies, results); }
/// <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); } }