public void Parse_Invalid() { try { NameValueHeaderValue.Parse(null); Assert.Fail("#1"); } catch (FormatException) { } try { NameValueHeaderValue.Parse(" "); Assert.Fail("#2"); } catch (FormatException) { } try { NameValueHeaderValue.Parse("a;b"); Assert.Fail("#3"); } catch (FormatException) { } try { NameValueHeaderValue.Parse("c = 1;"); Assert.Fail("#3"); } catch (FormatException) { } }
private void CheckInvalidParse(string input) { Assert.Throws <FormatException>(() => { NameValueHeaderValue.Parse(input); }); Assert.False(NameValueHeaderValue.TryParse(input, out NameValueHeaderValue result)); Assert.Null(result); }
private void AssertHeadersAreInjected(List <string> requestLines, Activity parent) { string requestId = null; var correlationContext = new List <NameValueHeaderValue>(); foreach (var line in requestLines) { if (line.StartsWith("Request-Id")) { requestId = line.Substring("Request-Id".Length).Trim(' ', ':'); } if (line.StartsWith("Correlation-Context")) { var corrCtxString = line.Substring("Correlation-Context".Length).Trim(' ', ':'); foreach (var kvp in corrCtxString.Split(',')) { correlationContext.Add(NameValueHeaderValue.Parse(kvp)); } } } Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled"); Assert.True(requestId.StartsWith(parent.Id)); Assert.NotEqual(parent.Id, requestId); List <KeyValuePair <string, string> > baggage = parent.Baggage.ToList(); Assert.Equal(baggage.Count, correlationContext.Count); foreach (var kvp in baggage) { Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext); } }
/// <summary> /// Adds the minimum set of headers to prevent browser caching. /// </summary> /// <param name="response"></param> /// <returns></returns> internal static void AddNoCacheHeaders(HttpResponseMessage response) { // see: http://stackoverflow.com/a/2068407 response.Headers.CacheControl = new CacheControlHeaderValue() { NoStore = true, NoCache = true }; response.Headers.Pragma.Add(NameValueHeaderValue.Parse("no-cache")); }
public HttpClient Client(TimeSpan?timeout = null) { return(new HttpClient { Timeout = timeout ?? TimeSpan.FromSeconds(100), DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"), Pragma = { NameValueHeaderValue.Parse("no-cache") } } }); }
public void Parse() { var res = NameValueHeaderValue.Parse("c"); Assert.AreEqual("c", res.Name, "#1"); Assert.IsNull(res.Value, "#1a"); res = NameValueHeaderValue.Parse("c = 1"); Assert.AreEqual("c", res.Name, "#2"); Assert.AreEqual("1", res.Value, "#2a"); Assert.AreEqual("c=1", res.ToString(), "#2b"); res = NameValueHeaderValue.Parse("c = \"1\""); Assert.AreEqual("c", res.Name, "#3"); Assert.AreEqual("\"1\"", res.Value, "#3a"); Assert.AreEqual("c=\"1\"", res.ToString(), "#3b"); }
private void CheckValidParse(string input, NameValueHeaderValue expectedResult) { NameValueHeaderValue result = NameValueHeaderValue.Parse(input); Assert.Equal(expectedResult, result); Assert.True(NameValueHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); // New lines are never allowed for (int i = 0; i < input.Length; i++) { CheckInvalidParse(input.Insert(i, "\r")); CheckInvalidParse(input.Insert(i, "\n")); CheckInvalidParse(input.Insert(i, "\r\n")); CheckInvalidParse(input.Insert(i, "\r\n ")); } }
public HttpClient Client(TimeSpan?timeout = null) { var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration; configuration.TimeoutIntervalForRequest = timeout?.Seconds ?? 100; var handler = new NSUrlSessionHandler(configuration) { DisableCaching = true }; return(new HttpClient(handler) { DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"), Pragma = { NameValueHeaderValue.Parse("no-cache") } } }); }
public CDOSession(CDOSessionOptions options) { Options = options; Instance = this; //used by cdo when no session object is passed //init httpclient HttpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }); //HttpClient = new HttpClient(new HttpClientHandler() { SslProtocols = _options.SslProtocols }); //this is not supported in older frameworks & problematic in Outlook VSTO ServicePointManager.SecurityProtocol = Options.SecurityProtocol; HttpClient.DefaultRequestHeaders.ConnectionClose = false; HttpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); HttpClient.DefaultRequestHeaders.Pragma.Add(NameValueHeaderValue.Parse("no-cache")); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Task.Factory.StartNew(() => NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged).Wait(); }
async Task <HttpResponseMessage> InternalExecuteRequest(HttpRequestMessage request) { var handler = new HttpClientHandler(); #if DEBUG handler.ServerCertificateCustomValidationCallback += (s, c, ch, e) => { return(true); }; #endif var client = new HttpClient(handler) { Timeout = TimeSpan.FromMinutes(1.5), DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"), Pragma = { NameValueHeaderValue.Parse("no-cache") } } }; return(await client.SendAsync(request)); }
async Task <T> InternalExecuteAsync <T>(IHttpRequest restRequest) where T : class { var finalUri = BuildUri(restRequest); #if DEBUG Console.WriteLine($"ExecuteAsync: {restRequest.Method}: {finalUri}"); Console.WriteLine($"Request:{Environment.NewLine}{restRequest}"); #endif object data = default(T); var provider = Xamarin.Forms.DependencyService.Get <IHttpClientProvider>(); var client = new System.Net.Http.HttpClient(new HttpClientHandler()) { Timeout = TimeSpan.FromMinutes(1.5), DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"), Pragma = { NameValueHeaderValue.Parse("no-cache") } } }; var request = new HttpRequestMessage(restRequest.Method.ToHttpMethod(), finalUri); request.Headers.CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"); try { request.Content = GetContent(restRequest); foreach (var header in restRequest.Headers) { request.Headers.Add(header.Key, header.Value); } var response = await client.SendAsync(request); var content = ""; if (response.IsSuccessStatusCode) { if (typeof(T) == typeof(FileObject)) { var file = new FileObject { Data = await response.Content.ReadAsByteArrayAsync(), FileName = response.Content.Headers.ContentDisposition.FileName.Trim('"') }; data = file; } else { content = await response.Content.ReadAsStringAsync(); #if DEBUG Console.WriteLine($"{response.StatusCode} : {content}"); #endif data = (typeof(T).IsPrimitive || typeof(T) == typeof(string)) ? content as T : JsonConvert.DeserializeObject <T>( content, new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc }); } } else { if (response.StatusCode == HttpStatusCode.Unauthorized) { UnAuthorizedEventHandler?.Invoke(); } else { content = await response.Content.ReadAsStringAsync(); } throw new HttpServerException(response.StatusCode, content); } } catch (HttpServerException e) { throw new HttpServerException(e.StatusCode, e.Message); } catch (Exception e) { #if DEBUG Console.WriteLine($"{e.Message} : {e.StackTrace}"); #endif throw new HttpConnectionException(); } return((T)data); }
private void CheckInvalidParse(string?input) { Assert.Throws <FormatException>(() => NameValueHeaderValue.Parse(input)); }
private void CheckValidParse(string?input, NameValueHeaderValue expectedResult) { var result = NameValueHeaderValue.Parse(input); Assert.Equal(expectedResult, result); }
internal static async Task <ResultSegment <TElement> > TableQueryPostProcessGenericAsync <TElement, TQueryType>(Stream responseStream, Func <string, string, DateTimeOffset, IDictionary <string, EntityProperty>, string, TElement> resolver, HttpResponseMessage resp, TableRequestOptions options, OperationContext ctx, CancellationToken cancellationToken) { ResultSegment <TElement> retSeg = new ResultSegment <TElement>(new List <TElement>()) { ContinuationToken = ContinuationFromResponse(resp) }; MediaTypeHeaderValue contentType = resp.Content.Headers.ContentType; if (contentType.MediaType.Equals("application/json") && contentType.Parameters.Contains(NameValueHeaderValue.Parse("odata=nometadata"))) { await ReadQueryResponseUsingJsonParserAsync(retSeg, responseStream, resp.Headers.ETag?.Tag, resolver, options.PropertyResolver, typeof(TQueryType), null, options, cancellationToken); } else { foreach (KeyValuePair <string, Dictionary <string, object> > item in await ReadQueryResponseUsingJsonParserMetadataAsync(responseStream, cancellationToken)) { retSeg.Results.Add(ReadAndResolve(item.Key, item.Value, resolver, options)); } } Logger.LogInformational(ctx, "Retrieved '{0}' results with continuation token '{1}'.", retSeg.Results.Count, retSeg.ContinuationToken); return(retSeg); }
internal static async Task <TableResult> TableOperationPostProcessAsync(TableResult result, TableOperation operation, RESTCommand <TableResult> cmd, HttpResponseMessage resp, OperationContext ctx, TableRequestOptions options, string accountName, CancellationToken cancellationToken) { string text = (resp.Headers.ETag != null) ? resp.Headers.ETag.ToString() : null; if (operation.OperationType != TableOperationType.Retrieve && operation.OperationType != 0) { result.Etag = text; operation.Entity.ETag = result.Etag; } else if (operation.OperationType == TableOperationType.Insert && !operation.EchoContent) { if (text != null) { result.Etag = text; operation.Entity.ETag = result.Etag; operation.Entity.Timestamp = ParseETagForTimestamp(result.Etag); } } else { MediaTypeHeaderValue contentType = resp.Content.Headers.ContentType; if (!contentType.MediaType.Equals("application/json") || !contentType.Parameters.Contains(NameValueHeaderValue.Parse("odata=nometadata"))) { await ReadOdataEntityAsync(result, operation, cmd.ResponseStream, ctx, accountName, options, cancellationToken); } else { result.Etag = text; await ReadEntityUsingJsonParserAsync(result, operation, cmd.ResponseStream, ctx, options, cancellationToken); } } return(result); }
public DefaultResponse RedirectRequest(ServerInfo server, HttpRequest request) { try { var badRequestErrorMessage = "can't forward request. invalid parameters"; var headers = request.Headers; var contentType = "application/json"; var endPoint = string.Empty; var method = string.Empty; var queryString = string.Empty; if (!headers.ContainsKey("Original-Path")) { throw new BadRequestException(badRequestErrorMessage); } if (!headers.ContainsKey("Original-Method")) { throw new BadRequestException(badRequestErrorMessage); } if (headers.ContainsKey("Original-ContentType")) { contentType = headers["Original-ContentType"]; } if (headers.ContainsKey("Original-QueryString")) { queryString = headers["Original-QueryString"]; } endPoint = headers["Original-Path"]; method = headers["Original-Method"]; var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls, ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true }; var requestToken = _authService.GenerateTokenForServerRequest(server); var httpClient = new HttpClient(handler); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", requestToken); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = null; var contentTypeParameters = contentType.Split(";"); contentType = contentTypeParameters[0]; var mediaTypeHeaderValue = new MediaTypeHeaderValue(contentType); for (var i = 1; i < contentTypeParameters.Length; i++) { mediaTypeHeaderValue.Parameters.Add(NameValueHeaderValue.Parse(contentTypeParameters[i])); } var requestMessage = new HttpRequestMessage(); requestMessage.RequestUri = new Uri($"{server.BaseUrl}/{endPoint}{queryString}"); switch (method) { case "GET": requestMessage.Method = new HttpMethod("GET"); response = httpClient.SendAsync(requestMessage).Result; break; case "POST": using (var scontent = new StreamContent(request.Body) { Headers = { ContentType = mediaTypeHeaderValue } }) { requestMessage.Method = new HttpMethod("POST"); requestMessage.Content = scontent; response = httpClient.SendAsync(requestMessage).Result; } break; case "PUT": using (var scontent = new StreamContent(request.Body) { Headers = { ContentType = mediaTypeHeaderValue } }) { requestMessage.Method = new HttpMethod("PUT"); requestMessage.Content = scontent; response = httpClient.SendAsync(requestMessage).Result; } break; case "DELETE": requestMessage.Method = new HttpMethod("DELETE"); response = httpClient.SendAsync(requestMessage).Result; break; default: throw new BadRequestException(badRequestErrorMessage); } var returnedObjectContent = response.Content.ReadAsStringAsync().Result; var deserializedObject = JsonConvert.DeserializeObject(returnedObjectContent); var forwardResponse = new DefaultResponse { StatusCode = (int)response.StatusCode, Body = deserializedObject }; return(forwardResponse); } catch (Exception e) { _logService.logExceptionOnDatabase(e); throw new InternalServerError("error while establishing connection with remote server"); } }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.Headers.Contains("Forwarded")) { try { var header = request.Headers.GetValues("Forwarded").First(); var forwardedHeader = header.Split(';').Where(nv => !string.IsNullOrEmpty(nv)).Select(nv => NameValueHeaderValue.Parse(nv)).ToDictionary(nv => nv.Name, nv => nv.Value); var gatewayUrl = new Uri(string.Format("{0}://{1}", forwardedHeader["proto"], forwardedHeader["host"])); request.Properties[ConferenceWebApi.Tools.HttpRequestMessageExtensions.GatewayUrlKey] = gatewayUrl; } catch (Exception ex) { return(Task.FromResult <HttpResponseMessage>(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Failed to parse Forwarded header : " + ex.Message) })); } } return(base.SendAsync(request, cancellationToken)); }
internal static StorageRequestMessage BuildStorageRequestMessageForTableBatchOperation(Uri uri, TableBatchOperation batch, ICanonicalizer canonicalizer, string tableName, StorageCredentials cred, OperationContext ctx, TableRequestOptions options) { StorageRequestMessage storageRequestMessage = new StorageRequestMessage(HttpMethod.Post, NavigationHelper.AppendPathToSingleUri(uri, "$batch"), canonicalizer, cred, cred.AccountName); storageRequestMessage.Headers.AcceptCharset.ParseAdd("UTF-8"); storageRequestMessage.Headers.Add("MaxDataServiceVersion", "3.0;NetFx"); TablePayloadFormat value = options.PayloadFormat.Value; Logger.LogInformational(ctx, "Setting payload format for the request to '{0}'.", value); SetAcceptHeaderValueForStorageRequestMessage(storageRequestMessage, value); storageRequestMessage.Headers.Add("DataServiceVersion", "3.0;"); MultiBufferMemoryStream multiBufferMemoryStream = new MultiBufferMemoryStream(); string str = Guid.NewGuid().ToString(); using (StreamWriter streamWriter = new StreamWriter(new NonCloseableStream(multiBufferMemoryStream))) { string str2 = Guid.NewGuid().ToString(); string text = "--batch_" + str; string text2 = "--changeset_" + str2; string text3 = "Accept: "; switch (value) { case TablePayloadFormat.Json: text3 += "application/json;odata=minimalmetadata"; break; case TablePayloadFormat.JsonFullMetadata: text3 += "application/json;odata=fullmetadata"; break; case TablePayloadFormat.JsonNoMetadata: text3 += "application/json;odata=nometadata"; break; } streamWriter.WriteLine(text); bool flag = batch.Count == 1 && batch[0].OperationType == TableOperationType.Retrieve; if (!flag) { streamWriter.WriteLine("Content-Type: multipart/mixed; boundary=changeset_" + str2); streamWriter.WriteLine(); } foreach (TableOperation item in batch) { HttpMethod httpMethod = RESTCommandGeneratorUtils.ExtractHttpMethod(item); if (item.OperationType == TableOperationType.Merge || item.OperationType == TableOperationType.InsertOrMerge) { httpMethod = new HttpMethod("MERGE"); } if (!flag) { streamWriter.WriteLine(text2); } streamWriter.WriteLine("Content-Type: application/http"); streamWriter.WriteLine("Content-Transfer-Encoding: binary"); streamWriter.WriteLine(); string text4 = Uri.EscapeUriString(RESTCommandGeneratorUtils.GenerateRequestURI(item, uri, tableName).ToString()); text4 = text4.Replace("%25", "%"); streamWriter.WriteLine(httpMethod + " " + text4 + " HTTP/1.1"); streamWriter.WriteLine(text3); streamWriter.WriteLine("Content-Type: application/json"); if (item.OperationType == TableOperationType.Insert) { streamWriter.WriteLine("Prefer: " + (item.EchoContent ? "return-content" : "return-no-content")); } streamWriter.WriteLine("DataServiceVersion: 3.0;"); if (item.OperationType == TableOperationType.Delete || item.OperationType == TableOperationType.Replace || item.OperationType == TableOperationType.Merge) { streamWriter.WriteLine("If-Match: " + item.ETag); } streamWriter.WriteLine(); if (item.OperationType != TableOperationType.Delete && item.OperationType != TableOperationType.Retrieve) { using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter)) { jsonTextWriter.CloseOutput = false; WriteEntityContent(item, ctx, options, jsonTextWriter); } streamWriter.WriteLine(); } } if (!flag) { streamWriter.WriteLine(text2 + "--"); } streamWriter.WriteLine(text + "--"); } multiBufferMemoryStream.Seek(0L, SeekOrigin.Begin); storageRequestMessage.Content = new StreamContent(multiBufferMemoryStream); storageRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/mixed"); storageRequestMessage.Content.Headers.ContentType.Parameters.Add(NameValueHeaderValue.Parse("boundary=batch_" + str)); return(storageRequestMessage); }