private void AddCallerHeaders(HttpContentHeaders headers, CallerDescriptor caller) { if (caller == null) { return; } if (!string.IsNullOrEmpty(caller.IntentId)) { headers.TryAddWithoutValidation(DasyncHttpHeaders.CallerIntentId, caller.IntentId); } if (caller.Service != null) { headers.TryAddWithoutValidation(DasyncHttpHeaders.CallerServiceName, caller.Service.Name); if (!string.IsNullOrEmpty(caller.Service.Proxy)) { headers.TryAddWithoutValidation(DasyncHttpHeaders.CallerServiceProxy, caller.Service.Proxy); } } if (caller.Method != null) { headers.TryAddWithoutValidation(DasyncHttpHeaders.CallerMethodName, caller.Method.Name); } if (caller.Event != null) { headers.TryAddWithoutValidation(DasyncHttpHeaders.CallerEventName, caller.Event.Name); } }
public override void AppendRequestHeaders(HttpContentHeaders headerCollection) { if (_lastModified.HasValue) { headerCollection.TryAddWithoutValidation("If-Modified-Since", _lastModified.Value.ToServerTime(true)); } if (!string.IsNullOrEmpty(_langCode)) { headerCollection.TryAddWithoutValidation("Accept-Language", _langCode); } }
/// <inheritdoc/> public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { // Determine the content type or let base class handle it. MediaTypeHeaderValue newMediaType = null; if (ODataOutputFormatterHelper.TryGetContentHeader(type, mediaType, out newMediaType)) { headers.ContentType = newMediaType; } else { // This is the case when a user creates a new ObjectContent<T> passing in a null mediaType base.SetDefaultContentHeaders(type, headers, mediaType); } // Set the character set. IEnumerable <string> acceptCharsetValues = Request.Headers.AcceptCharset.Select(cs => cs.Value); string newCharSet = String.Empty; if (ODataOutputFormatterHelper.TryGetCharSet(headers.ContentType, acceptCharsetValues, out newCharSet)) { headers.ContentType.CharSet = newCharSet; } // Add version header. headers.TryAddWithoutValidation( ODataVersionConstraint.ODataServiceVersionHeader, ODataUtils.ODataVersionToString(ResultHelpers.GetODataResponseVersion(Request))); }
public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers = new HttpContentHeaders(() => { throw new ShouldNotBeInvokedException(); }); _headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n "); Assert.Equal(68, _headers.ContentLength); }
internal static void AddContentTypeJson(this HttpContentHeaders headers) { const string contentType = "Content-Type"; const string applicationJson = "application/json"; headers.TryAddWithoutValidation(contentType, applicationJson); }
/// <summary> /// SetHeaders. /// </summary> /// <param name="contentDispositionName">contentDispositionName.</param> /// <param name="headers">headers.</param> protected virtual void SetHeaders( string contentDispositionName, HttpContentHeaders headers) { if (this.Headers.ContainsKey("content-type")) { bool isContentTypeValid = MediaTypeHeaderValue.TryParse(this.Headers["content-type"].FirstOrDefault(), out var parsedContentType); if (isContentTypeValid) { headers.ContentType = parsedContentType; } } headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = contentDispositionName, }; var headersList = this.Headers.Where(kv => !this.IsReservedHeader(kv.Key)); foreach (var header in headersList) { headers.TryAddWithoutValidation(header.Key, header.Value); } }
public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers = new HttpContentHeaders(() => { Assert.True(false, "Delegate called."); return(0); }); _headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n "); Assert.Equal(68, _headers.ContentLength); }
public override void AppendRequestHeaders(HttpContentHeaders headerCollection) { if (!string.IsNullOrEmpty(_langCode)) { headerCollection.TryAddWithoutValidation("Accept-Language", _langCode); } }
private HttpResponseMsg CreateResponseMessage(HttpWebResponse webResponse, HttpRequestMessage request) { var httpResponseMessage = new HttpResponseMsg(webResponse.StatusCode) { ReasonPhrase = webResponse.StatusDescription, Version = webResponse.ProtocolVersion, RequestMessage = request }; httpResponseMessage.Content = new ResponseContent(new ResponseStreamWrapper(webResponse)); request.RequestUri = webResponse.ResponseUri; WebHeaderCollection headers = webResponse.Headers; HttpContentHeaders headers2 = httpResponseMessage.Content.Headers; HttpResponseHeaders headers3 = httpResponseMessage.Headers; if (webResponse.ContentLength >= 0L) { headers2.ContentLength = new long?(webResponse.ContentLength); } for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); if (string.Compare(key, "Content-Length", StringComparison.OrdinalIgnoreCase) != 0) { string[] values = headers.GetValues(i); if (!headers3.TryAddWithoutValidation(key, values)) { bool flag = headers2.TryAddWithoutValidation(key, values); } } } return(httpResponseMessage); }
/// <inheritdoc/> public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { // call base to validate parameters and set Content-Type header based on mediaType parameter. base.SetDefaultContentHeaders(type, headers, mediaType); headers.TryAddWithoutValidation(ODataServiceVersion, ODataUtils.ODataVersionToString(_version)); }
internal static void CopyTo(this HttpContentHeaders from, HttpContentHeaders to) { foreach (var header in from) { to.TryAddWithoutValidation(header.Key, header.Value); } }
/// <inheritdoc/> public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { if (headers == null) { throw Error.ArgumentNull("headers"); } // call base to validate parameters and set Content-Type header based on mediaType parameter. base.SetDefaultContentHeaders(type, headers, mediaType); ODataFormat format = GetODataFormat(headers); IEnumerable <KeyValuePair <string, string> > oDataHeaders = GetResponseMessageHeaders(type, format, _defaultODataVersion); foreach (KeyValuePair <string, string> pair in oDataHeaders) { // Special case Content-Type header so that we don't end up with two values for it // since base.SetDefaultContentHeaders could also have set it. if (String.Equals("Content-Type", pair.Key, StringComparison.OrdinalIgnoreCase)) { headers.ContentType = MediaTypeHeaderValue.Parse(pair.Value); } else { headers.TryAddWithoutValidation(pair.Key, pair.Value); } } }
private static void CopyContentHeaders(HttpContentHeaders source, HttpContentHeaders destination) { foreach (var header in source) { destination.TryAddWithoutValidation(header.Key, header.Value); } }
public override void SetDefaultContentHeaders( Type objectType, HttpContentHeaders contentHeaders, MediaTypeHeaderValue mediaType ) { base.SetDefaultContentHeaders(objectType, contentHeaders, mediaType); contentHeaders.TryAddWithoutValidation("Version", "1.3.5.0"); }
/// <inheritdoc/> public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { // Determine the content type or let base class handle it. MediaTypeHeaderValue newMediaType = null; if (ODataOutputFormatterHelper.TryGetContentHeader(type, mediaType, out newMediaType)) { headers.ContentType = newMediaType; } else { // This is the case when a user creates a new ObjectContent<T> passing in a null mediaType base.SetDefaultContentHeaders(type, headers, mediaType); } // Set the character set. IEnumerable <string> acceptCharsetValues = Request.Headers.AcceptCharset.Select(cs => cs.Value); string newCharSet = String.Empty; if (ODataOutputFormatterHelper.TryGetCharSet(headers.ContentType, acceptCharsetValues, out newCharSet)) { headers.ContentType.CharSet = newCharSet; } // Add version header. headers.TryAddWithoutValidation( ODataVersionConstraint.ODataServiceVersionHeader, ODataUtils.ODataVersionToString(ResultHelpers.GetODataResponseVersion(Request))); // Add Preference-Applied headers var responseMessage = ODataOutputFormatterHelper.PrepareResponseMessage( new WebApiRequestMessage(Request), new WebApiRequestHeaders(Request.Headers), (services) => ODataMessageWrapperHelper.Create(null, headers, services)); foreach (var header in responseMessage.Headers) { if (!headers.Contains(header.Key)) { headers.TryAddWithoutValidation(header.Key, header.Value); } } }
public static void CopyTo(this HttpContentHeaders fromHeaders, HttpContentHeaders toHeaders) { Contract.Assert(fromHeaders != null, "fromHeaders cannot be null."); Contract.Assert(toHeaders != null, "toHeaders cannot be null."); foreach (KeyValuePair <string, IEnumerable <string> > header in fromHeaders) { toHeaders.TryAddWithoutValidation(header.Key, header.Value); } }
/// <inheritdoc/> public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { if (type == null) { throw Error.ArgumentNull("type"); } if (headers == null) { throw Error.ArgumentNull("headers"); } // When the user asks for application/json we really need to set the content type to // application/json; odata.metadata=minimal. If the user provides the media type and is // application/json we are going to add automatically odata.metadata=minimal. Otherwise we are // going to fallback to the default implementation. // When calling this formatter as part of content negotiation the content negotiator will always // pick a non null media type. In case the user creates a new ObjectContent<T> and doesn't pass in a // media type, we delegate to the base class to rely on the default behavior. It's the user's // responsibility to pass in the right media type. if (mediaType != null) { if (mediaType.MediaType.Equals("application/json", StringComparison.OrdinalIgnoreCase) && !mediaType.Parameters.Any(p => p.Name.Equals("odata.metadata", StringComparison.OrdinalIgnoreCase))) { mediaType.Parameters.Add(new NameValueHeaderValue("odata.metadata", "minimal")); } headers.ContentType = (MediaTypeHeaderValue)((ICloneable)mediaType).Clone(); } else { // This is the case when a user creates a new ObjectContent<T> passing in a null mediaType base.SetDefaultContentHeaders(type, headers, mediaType); } // In general, in Web API we pick a default charset based on the supported character sets // of the formatter. However, according to the OData spec, the service shouldn't be sending // a character set unless explicitly specified, so if the client didn't send the charset we chose // we just clean it. if (headers.ContentType != null && !Request.Headers.AcceptCharset .Any(cs => cs.Value.Equals(headers.ContentType.CharSet, StringComparison.OrdinalIgnoreCase))) { headers.ContentType.CharSet = String.Empty; } headers.TryAddWithoutValidation( HttpRequestMessageProperties.ODataServiceVersionHeader, ODataUtils.ODataVersionToString(_version)); }
/// <summary> /// Copies the unsorted header fields to a sorted collection. /// </summary> /// <param name="source">The unsorted source headers</param> /// <param name="destination">The destination <see cref="HttpRequestHeaders"/> or <see cref="HttpResponseHeaders"/>.</param> /// <param name="contentStream">The input <see cref="Stream"/> used to form any <see cref="HttpContent"/> being part of this HTTP request.</param> /// <param name="rewind">Start location of any request entity within the <paramref name="contentStream"/>.</param> /// <returns>An <see cref="HttpContent"/> instance if header fields contained and <see cref="HttpContentHeaders"/>.</returns> private static HttpContent CreateHeaderFields( HttpHeaders source, HttpHeaders destination, Stream contentStream, int rewind ) { Contract.Assert(source != null, "source headers cannot be null"); Contract.Assert(destination != null, "destination headers cannot be null"); Contract.Assert(contentStream != null, "contentStream must be non null"); HttpContentHeaders contentHeaders = null; HttpContent content = null; // Set the header fields foreach (KeyValuePair <string, IEnumerable <string> > header in source) { if (!destination.TryAddWithoutValidation(header.Key, header.Value)) { if (contentHeaders == null) { contentHeaders = FormattingUtilities.CreateEmptyContentHeaders(); } contentHeaders.TryAddWithoutValidation(header.Key, header.Value); } } // If we have content headers then create an HttpContent for this Response if (contentHeaders != null) { // Need to rewind the input stream to be at the position right after the HTTP header // which we may already have parsed as we read the content stream. if (!contentStream.CanSeek) { throw Error.InvalidOperation( Properties.Resources.HttpMessageContentStreamMustBeSeekable, "ContentReadStream", FormattingUtilities.HttpResponseMessageType.Name ); } contentStream.Seek(0 - rewind, SeekOrigin.Current); content = new StreamContent(contentStream); contentHeaders.CopyTo(content.Headers); } return(content); }
private static void ParseResponseHeaders( SafeWinHttpHandle requestHandle, HttpResponseMessage response, char[] buffer, bool stripEncodingHeaders) { HttpResponseHeaders responseHeaders = response.Headers; HttpContentHeaders contentHeaders = response.Content.Headers; int bufferLength = GetResponseHeader( requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF, buffer); var reader = new WinHttpResponseHeaderReader(buffer, 0, bufferLength); // Skip the first line which contains status code, etc. information that we already parsed. reader.ReadLine(); // Parse the array of headers and split them between Content headers and Response headers. string headerName; string headerValue; while (reader.ReadHeader(out headerName, out headerValue)) { if (!responseHeaders.TryAddWithoutValidation(headerName, headerValue)) { if (stripEncodingHeaders) { // Remove Content-Length and Content-Encoding headers if we are // decompressing the response stream in the handler (due to // WINHTTP not supporting it in a particular downlevel platform). // This matches the behavior of WINHTTP when it does decompression itself. if (string.Equals(HttpKnownHeaderNames.ContentLength, headerName, StringComparison.OrdinalIgnoreCase) || string.Equals(HttpKnownHeaderNames.ContentEncoding, headerName, StringComparison.OrdinalIgnoreCase)) { continue; } } // TODO: Issue #2165. Should we log if there is an error here? contentHeaders.TryAddWithoutValidation(headerName, headerValue); } } }
private HttpResponseMessage CreateResponseMessage(HttpWebResponse webResponse, HttpRequestMessage request) { HttpResponseMessage response = new HttpResponseMessage(webResponse.StatusCode); response.ReasonPhrase = webResponse.StatusDescription; response.Version = webResponse.ProtocolVersion; response.RequestMessage = request; response.Content = new StreamContent(new WebExceptionWrapperStream(webResponse.GetResponseStream())); // Update Request-URI to reflect the URI actually leading to the response message. request.RequestUri = webResponse.ResponseUri; WebHeaderCollection webResponseHeaders = webResponse.Headers; HttpContentHeaders contentHeaders = response.Content.Headers; HttpResponseHeaders responseHeaders = response.Headers; // HttpWebResponse.ContentLength is set to -1 if no Content-Length header is provided. if (webResponse.ContentLength >= 0) { contentHeaders.ContentLength = webResponse.ContentLength; } for (int i = 0; i < webResponseHeaders.Count; i++) { string currentHeader = webResponseHeaders.GetKey(i); // We already set Content-Length if (string.Compare(currentHeader, HttpKnownHeaderNames.ContentLength, StringComparison.OrdinalIgnoreCase) == 0) { continue; } string[] values = webResponseHeaders.GetValues(i); if (!responseHeaders.TryAddWithoutValidation(currentHeader, values)) { bool result = contentHeaders.TryAddWithoutValidation(currentHeader, values); // WebHeaderCollection should never return us invalid header names. Contract.Assert(result, "Invalid header name."); } } return(response); }
private HttpResponseMsg CreateResponseMessage(HttpWebResponse webResponse, HttpRequestMessage request) { var httpResponseMessage = new HttpResponseMsg(webResponse.StatusCode); httpResponseMessage.ReasonPhrase = webResponse.StatusDescription; httpResponseMessage.Version = webResponse.ProtocolVersion; httpResponseMessage.RequestMessage = request; var content = new MemoryTributary(); using (var stream = webResponse.GetResponseStream()) { stream.CopyTo(content); } content.Position = 0; httpResponseMessage.Content = new ResponseContent(content); request.RequestUri = webResponse.ResponseUri; WebHeaderCollection headers = webResponse.Headers; HttpContentHeaders headers2 = httpResponseMessage.Content.Headers; HttpResponseHeaders headers3 = httpResponseMessage.Headers; if (webResponse.ContentLength >= 0L) { headers2.ContentLength = new long?(webResponse.ContentLength); } for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); if (string.Compare(key, "Content-Length", StringComparison.OrdinalIgnoreCase) != 0) { string[] values = headers.GetValues(i); if (!headers3.TryAddWithoutValidation(key, values)) { bool flag = headers2.TryAddWithoutValidation(key, values); } } } webResponse.Close(); return(httpResponseMessage); }
private void AddAsyncHeader(HttpContentHeaders headers, bool preferAsync, TimeSpan?waitTime = null) { if (!preferAsync && !waitTime.HasValue) { return; } var headerValue = preferAsync ? "respond-async" : null; if (waitTime.HasValue) { if (headerValue != null) { headerValue += ", "; } headerValue += "wait="; headerValue += (int)waitTime.Value.TotalSeconds; } headers.TryAddWithoutValidation("Prefer", headerValue); }
private void AddContentHeaders( HttpContentHeaders dotNetHeaders, Dictionary <string, string> contentHeaders ) { if (contentHeaders == null) { return; } foreach (var pair in contentHeaders) { if (!dotNetHeaders.TryAddWithoutValidation(pair.Key, pair.Value)) { throw new ArgumentException( $"The header {pair.Key} cannot be specified via the " + $"method {nameof(Attach)}. The header probably " + $"refers to the whole request and so cannot be " + $"attached to a content part." ); } } }
private void AddRetryHeader(HttpContentHeaders headers, int retryCount) { headers.TryAddWithoutValidation(DasyncHttpHeaders.Retry, retryCount > 0 ? "true" : "false"); }
public void ContentType_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value"); MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain"); value.CharSet = "utf-8"; value.Parameters.Add(new NameValueHeaderValue("custom", "value")); Assert.Equal(value, _headers.ContentType); }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { var _httpClient = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = false }); string curPort = ""; if (context.Request.Query.TryGetValue("port", out StringValues forcedPort)) { context.Response.Cookies.Delete("port"); context.Response.Cookies.Append("port", forcedPort); curPort = forcedPort; } else { if (context.Request.Cookies.TryGetValue("port", out string cachedPort)) { curPort = cachedPort; } } if (!_portMappings.Contains(curPort)) { await next.Invoke(context); } HttpRequestMessage request = new HttpRequestMessage(); if (!string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase) && !string.Equals(context.Request.Method, "HEAD", StringComparison.OrdinalIgnoreCase) && (!string.Equals(context.Request.Method, "DELETE", StringComparison.OrdinalIgnoreCase) && !string.Equals(context.Request.Method, "TRACE", StringComparison.OrdinalIgnoreCase))) { StreamContent streamContent = new StreamContent(context.Request.Body); request.Content = streamContent; } foreach (KeyValuePair <string, StringValues> header in context.Request.Headers) { HttpRequestHeaders headers1 = request.Headers; string key1 = header.Key; StringValues stringValues = header.Value; string[] array1 = stringValues.ToArray(); if (!headers1.TryAddWithoutValidation(key1, array1) && request.Content != null) { HttpContent content = request.Content; if (content != null) { HttpContentHeaders headers2 = content.Headers; string key2 = header.Key; stringValues = header.Value; string[] array2 = stringValues.ToArray(); headers2.TryAddWithoutValidation(key2, array2); } } } request.Headers.Host = $"localhost:{curPort}"; string uriString = $"http://localhost:{ curPort}{ context.Request.PathBase}{ context.Request.Path}{ context.Request.QueryString}"; request.RequestUri = new Uri(uriString); request.Method = new HttpMethod(context.Request.Method); HttpResponseMessage responseMessage = null; try { responseMessage = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted); // 处理重定向 if (responseMessage.StatusCode == HttpStatusCode.MovedPermanently) { context.Response.Redirect(responseMessage.Headers.Location.ToString()); } context.Response.StatusCode = (int)responseMessage.StatusCode; foreach (KeyValuePair <string, IEnumerable <string> > header in responseMessage.Headers) { context.Response.Headers[header.Key] = header.Value.ToArray(); } foreach (KeyValuePair <string, IEnumerable <string> > header in responseMessage.Content.Headers) { context.Response.Headers[header.Key] = header.Value.ToArray(); } context.Response.Headers.Remove("transfer-encoding"); //// 避免重定向引起的页面缓存 //if (context.Response.Headers.TryGetValue("Cache-Control",out _)) //{ // context.Response.Headers.Remove("Cache-Control"); //} //context.Response.Headers.Add("Cache-Control", "must-revalidate"); await responseMessage.Content.CopyToAsync(context.Response.Body); } catch (Exception e) { _logger.LogWarning(e, "代理访问调用失败,request:{request}", request.ToJson()); await next.Invoke(context); } finally { responseMessage?.Dispose(); } }