public HttpResponse(HttpResponseStatus status, string contentType = DEFAULT_CONTENT_TYPE, string charset = DEFAULT_CHARSET)
        {
            try
            {
                Encoding = Encoding.GetEncoding(charset);
            }
            catch { Encoding = Encoding.UTF8; }

            Cookies = new HttpCookies();

            Headers = new HttpResponseHeaders();
            Headers[HttpResponseHeaders.Date] = DateTime.Now.ToUniversalTime().ToString("r");
            Headers[HttpResponseHeaders.ContentType] = string.Format("{0}; charset={1}", contentType, charset);

            Status = status;
        }
Beispiel #2
0
        static CognitiveServicesResponse CreateResponseXLimitInfoObject(HttpResponseHeaders headers)
        {
            CognitiveServicesResponse responseLimitInfo = new CognitiveServicesResponse();

            foreach (var header in headers)
            {
                Console.WriteLine("CacheControl {0}={1}", header.Key, header.Value.FirstOrDefault());
                switch (header.Key)
                {
                case "Operation-Location": responseLimitInfo.OperationLocation = header.Value.FirstOrDefault(); break;

                case "X-RateLimit-Limit": responseLimitInfo.XRateLimitLimit = int.Parse(header.Value.FirstOrDefault()); break;

                case "X-RateLimit-Remaining": responseLimitInfo.XRateLimitRemaining = int.Parse(header.Value.FirstOrDefault()); break;

                case "X-RateLimit-Reset": responseLimitInfo.XRateLimitReset = Convert.ToDateTime(header.Value.FirstOrDefault()); break;

                default: break;
                }
            }
            ;

            return(responseLimitInfo);
        }
        public static IDictionary <string, string> ParseChallengeData(HttpResponseHeaders responseHeaders)
        {
            IDictionary <string, string> data = new Dictionary <string, string>();
            string wwwAuthenticate            = responseHeaders.GetValues(PKeyAuthConstants.WwwAuthenticateHeader).SingleOrDefault();

            wwwAuthenticate = wwwAuthenticate.Substring(PKeyAuthConstants.PKeyAuthName.Length + 1);
            if (string.IsNullOrEmpty(wwwAuthenticate))
            {
                return(data);
            }

            List <string> headerPairs = CoreHelpers.SplitWithQuotes(wwwAuthenticate, ',');

            foreach (string pair in headerPairs)
            {
                List <string> keyValue = CoreHelpers.SplitWithQuotes(pair, '=');
                if (keyValue.Count == 2)
                {
                    data.Add(keyValue[0].Trim(), keyValue[1].Trim().Replace("\"", ""));
                }
            }

            return(data);
        }
Beispiel #4
0
        public CatEnabledHeaderMissing(RemoteServiceFixtures.BasicMvcApplicationTestFixture fixture, ITestOutputHelper output)
        {
            _fixture            = fixture;
            _fixture.TestLogger = output;
            _fixture.Actions
            (
                setupConfiguration: () =>
            {
                var configPath     = fixture.DestinationNewRelicConfigFilePath;
                var configModifier = new NewRelicConfigModifier(configPath);

                configModifier.ForceTransactionTraces();

                CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(_fixture.DestinationNewRelicConfigFilePath, new[] { "configuration" }, "crossApplicationTracingEnabled", "true");
                CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(_fixture.DestinationNewRelicConfigFilePath, new[] { "configuration", "crossApplicationTracer" }, "enabled", "true");
            },
                exerciseApplication: () =>
            {
                _fixture.GetIgnored();
                _responseHeaders = _fixture.GetWithCatHeader(false);
            }
            );
            _fixture.Initialize();
        }
        /// <summary>
        /// Read Photo response headers
        /// </summary>
        /// <param name="responseHeaders">The response header.</param>
        internal override void ReadHeader(HttpResponseHeaders responseHeaders)
        {
            // Parse out the ETag, trimming the quotes
            if (responseHeaders.TryGetValues("ETag", out IEnumerable <string> etagValues))
            {
                var etag = etagValues.First();
                etag = etag.Replace("\"", "");

                if (etag.Length > 0)
                {
                    this.Results.EntityTag = etag;
                }
            }

            // Parse the Expires tag, leaving it in UTC
            if (responseHeaders.TryGetValues("Expires", out IEnumerable <string> expiresValues))
            {
                var expires = expiresValues.First();
                if (expires != null && expires.Length > 0)
                {
                    this.Results.Expires = DateTime.Parse(expires, null, DateTimeStyles.RoundtripKind);
                }
            }
        }
        public void Headers_ConnectionClose()
        {
            HttpResponseMessage message = new HttpResponseMessage();
            HttpResponseHeaders headers = message.Headers;

            Assert.IsNull(headers.ConnectionClose, "#1");

            headers.ConnectionClose = false;
            Assert.IsFalse(headers.ConnectionClose.Value, "#2");

            headers.Clear();

            headers.ConnectionClose = true;
            Assert.IsTrue(headers.ConnectionClose.Value, "#3");

            headers.Clear();
            headers.Connection.Add("Close");
            Assert.IsTrue(headers.ConnectionClose.Value, "#4");

            // .NET encloses the "Connection: Close" with two whitespaces.
            var normalized = Regex.Replace(message.ToString(), @"\s", "");

            Assert.AreEqual("StatusCode:200,ReasonPhrase:'OK',Version:1.1,Content:<null>,Headers:{Connection:Close}", normalized, "#5");
        }
        public CatDisabledChainedRequests(RemoteServiceFixtures.BasicMvcApplicationTestFixture fixture, ITestOutputHelper output) : base(fixture)
        {
            _fixture            = fixture;
            _fixture.TestLogger = output;
            _fixture.Actions
            (
                setupConfiguration: () =>
            {
                var configPath     = fixture.DestinationNewRelicConfigFilePath;
                var configModifier = new NewRelicConfigModifier(configPath);

                configModifier.ForceTransactionTraces();

                CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(_fixture.DestinationNewRelicConfigFilePath, new[] { "configuration" }, "crossApplicationTracingEnabled", "false");
                CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(_fixture.DestinationNewRelicConfigFilePath, new[] { "configuration", "crossApplicationTracer" }, "enabled", "false");
            },
                exerciseApplication: () =>
            {
                _fixture.GetIgnored();
                _responseHeaders = _fixture.GetWithCatHeaderChained(requestData: new CrossApplicationRequestData("guid", false, "tripId", "pathHash"));
            }
            );
            _fixture.Initialize();
        }
Beispiel #8
0
        private void SaveRateLimits(HttpResponseHeaders headers)
        {
            // X-RateLimit-Remaining: 45
            if (int.TryParse(headers.GetValues("X-RateLimit-Remaining").FirstOrDefault(), out int rateLimitRemaining))
            {
                _rateLimitRemaining = rateLimitRemaining;
                _log.LogInformation($"Rate Limit Remaining: {_rateLimitRemaining}");
            }
            else
            {
                throw new InvalidOperationException($"Could not parse X-RateLimit-Remaining: {headers.GetValues("X-RateLimit-Remaining").FirstOrDefault()}");
            }

            // X-RateLimit-Reset: 1372700873
            if (int.TryParse(headers.GetValues("X-RateLimit-Reset").FirstOrDefault(), out int rateLimitReset))
            {
                _rateLimitResetDateTime = DateTimeOffset.FromUnixTimeSeconds(rateLimitReset);
                _log.LogInformation($"Rate Limit Reset: {_rateLimitResetDateTime}");
            }
            else
            {
                throw new InvalidOperationException($"Could not parse X-RateLimit-Reset: {headers.GetValues("X-RateLimit-Reset").FirstOrDefault()}");
            }
        }
Beispiel #9
0
 private static Dictionary <string, string> GetRpcHeaders(HttpResponseHeaders headers)
 {
     return(headers
            .Where(it => it.Key.StartsWith(HeadPrefix))
            .ToDictionary(item => item.Key.Substring(HeadPrefix.Length, item.Key.Length - HeadPrefix.Length), item => item.Value.FirstOrDefault()));
 }
Beispiel #10
0
 private void SetErrorResponseHeaders(int statusCode)
 {
     StatusCode   = statusCode;
     ReasonPhrase = string.Empty;
     HttpResponseHeaders.Clear();
 }
Beispiel #11
0
 protected virtual void SetMissingRevFromRequestHeaders(DocumentResponse response, HttpResponseHeaders responseHeaders)
 {
     if (string.IsNullOrWhiteSpace(response.Rev))
     {
         response.Rev = responseHeaders.GetETag();
     }
 }
 public ValueTask <FlushResult> FirstWriteChunkedAsync(int statusCode, string reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, ReadOnlySpan <byte> data, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
 public GraphHttpException(int statusCode, string message, HttpResponseHeaders headers) : base(message)
 {
     this.StatusCode = statusCode;
     this.Headers    = headers;
 }
 protected virtual void SetMissingRevFromResponseHeaders <T>(EntityResponse <T> response, HttpResponseHeaders responseHeaders) where T : class
 {
     if (string.IsNullOrWhiteSpace(response.Rev))
     {
         response.Rev = responseHeaders.GetETag();
     }
 }
 public Response(HttpResponseHeaders headers, string response)
 {
     this.headers  = headers;
     this.response = response;
 }
 public void succ(Person p, HttpResponseHeaders rh)
 {
    Window.Alert(p.name);
 }
Beispiel #17
0
 public ContainerInfo(HttpResponseHeaders headers)
 {
     HeaderParsers.ParseHeaders(this, headers);
 }
 internal override void Parse(HttpResponseHeaders headers, object content, HttpStatusCode status)
 {
     base.Parse(headers, content, status);
 }
Beispiel #19
0
 private static IReadOnlyDictionary <string, IEnumerable <string> > ToDictionary(HttpResponseHeaders headers)
 {
     return(headers.ToDictionary(a => a.Key, a => a.Value));
 }
Beispiel #20
0
 /// <summary>
 /// Reads the headers from a HTTP response
 /// </summary>
 /// <param name="responseHeaders">a collection of response headers</param>
 internal virtual void ReadHeader(HttpResponseHeaders responseHeaders)
 {
 }
Beispiel #21
0
        private static async Task CopyProxyHttpResponse(HttpContext context, HttpResponseMessage responseMessage, CancellationToken cancellationToken)
        {
            context.Response.StatusCode = (int)responseMessage.StatusCode;
            HttpResponseHeaders headers = responseMessage.Headers;

            //TODO: Optimize these snippet codes
            //foreach (var header in responseMessage.Headers)
            //{
            //    context.Response.Headers[header.Key] = header.Value.ToArray();
            //}

            //foreach (var header in responseMessage.Content.Headers)
            //{
            //    context.Response.Headers[header.Key] = header.Value.ToArray();
            //}

            var test = responseMessage.Headers;

            //foreach (var header in responseMessage.Headers)
            //{
            //    context.Response.Headers[header.Key] = header.Value.ToArray();
            //}

            //foreach (var header in responseMessage.Content.Headers)
            //{
            //    context.Response.Headers[header.Key] = header.Value.ToArray();
            //}

            if (responseMessage.Headers.AcceptRanges.Count > 0)
            {
                context.Response.Headers.Set("accept-ranges", responseMessage.Headers.AcceptRanges.ToString());
            }

            if (responseMessage.Headers.Age != null)
            {
                context.Response.Headers.Set("age", responseMessage.Headers.Age.ToString());
            }

            if (responseMessage.Headers.Connection != null)
            {
                context.Response.Headers.Set("connection", responseMessage.Headers.Connection.ToString());
            }

            if (responseMessage.Headers.ETag != null)
            {
                context.Response.Headers.Set("etag", responseMessage.Headers.ETag.ToString());
            }

            if (responseMessage.Headers.Date != null)
            {
                context.Response.Headers.Set("date", responseMessage.Headers.Date.ToString());
            }

            if (responseMessage.Content.Headers.ContentType != null)
            {
                context.Response.Headers.Set("content-type", responseMessage.Content.Headers.ContentType.MediaType);
            }

            // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
            context.Response.Headers.Remove("transfer-encoding");

            using (var responseStream = await responseMessage.Content.ReadAsStreamAsync())
            {
                await responseStream.CopyToAsync(context.Response.OutputStream, StreamCopyBufferSize, cancellationToken);
            }
        }
Beispiel #22
0
 public WebPushException(string message, HttpStatusCode statusCode, HttpResponseHeaders headers, PushSubscription pushSubscription) : base(message)
 {
     StatusCode       = statusCode;
     Headers          = headers;
     PushSubscription = pushSubscription;
 }
        public ValueTask <FlushResult> FirstWriteAsync(int statusCode, string reasonPhrase, HttpResponseHeaders responseHeaders, bool autoChunk, ReadOnlySpan <byte> data, CancellationToken cancellationToken)
        {
            lock (_dataWriterLock)
            {
                WriteResponseHeaders(statusCode, reasonPhrase, responseHeaders, autoChunk, appCompleted: false);

                return(WriteDataToPipeAsync(data, cancellationToken));
            }
        }
Beispiel #24
0
 public static void SetCookie(this IAbpAntiForgeryManager manager, HttpResponseHeaders headers)
 {
     headers.SetCookie(new Cookie(manager.Configuration.TokenCookieName, manager.GenerateToken()));
 }
Beispiel #25
0
 public ApiResponse(HttpStatusCode statusCode, HttpResponseHeaders headers, string text)
 {
     StatusCode = statusCode;
     Headers    = headers;
     Text       = text;
 }
Beispiel #26
0
 public static string GetETag(this HttpResponseHeaders headers)
 {
     return(headers.ETag == null || headers.ETag.Tag == null
         ? string.Empty
         : headers.ETag.Tag.Substring(1, headers.ETag.Tag.Length - 2));
 }
Beispiel #27
0
 public ResponseContext(HttpStatusCode httpStatusCode, HttpResponseHeaders headers, Stream content)
 {
     StatusCode    = httpStatusCode;
     Headers       = headers;
     ContentStream = content;
 }
    public void Initialize_ChangeHeadersSource_EnumeratorUsesNewSource()
    {
        var responseHeaders = new HttpResponseHeaders();

        responseHeaders.Append("Name1", "Value1");
        responseHeaders.Append("Name2", "Value2-1");
        responseHeaders.Append("Name2", "Value2-2");

        var e = new Http3HeadersEnumerator();

        e.Initialize(responseHeaders);

        Assert.True(e.MoveNext());
        Assert.Equal("Name1", e.Current.Key);
        Assert.Equal("Value1", e.Current.Value);
        var(index, matchedValue) = e.GetQPackStaticTableId();
        Assert.Equal(-1, index);

        Assert.True(e.MoveNext());
        Assert.Equal("Name2", e.Current.Key);
        Assert.Equal("Value2-1", e.Current.Value);
        (index, matchedValue) = e.GetQPackStaticTableId();
        Assert.Equal(-1, index);

        Assert.True(e.MoveNext());
        Assert.Equal("Name2", e.Current.Key);
        Assert.Equal("Value2-2", e.Current.Value);
        (index, matchedValue) = e.GetQPackStaticTableId();
        Assert.Equal(-1, index);

        var responseTrailers = (IHeaderDictionary) new HttpResponseTrailers();

        responseTrailers.GrpcStatus = "1";

        responseTrailers.Append("Name1", "Value1");
        responseTrailers.Append("Name2", "Value2-1");
        responseTrailers.Append("Name2", "Value2-2");

        e.Initialize(responseTrailers);

        Assert.True(e.MoveNext());
        Assert.Equal("Grpc-Status", e.Current.Key);
        Assert.Equal("1", e.Current.Value);
        (index, matchedValue) = e.GetQPackStaticTableId();
        Assert.Equal(-1, index);

        Assert.True(e.MoveNext());
        Assert.Equal("Name1", e.Current.Key);
        Assert.Equal("Value1", e.Current.Value);
        (index, matchedValue) = e.GetQPackStaticTableId();
        Assert.Equal(-1, index);

        Assert.True(e.MoveNext());
        Assert.Equal("Name2", e.Current.Key);
        Assert.Equal("Value2-1", e.Current.Value);
        (index, matchedValue) = e.GetQPackStaticTableId();
        Assert.Equal(-1, index);

        Assert.True(e.MoveNext());
        Assert.Equal("Name2", e.Current.Key);
        Assert.Equal("Value2-2", e.Current.Value);
        (index, matchedValue) = e.GetQPackStaticTableId();
        Assert.Equal(-1, index);

        Assert.False(e.MoveNext());
    }
Beispiel #29
0
 private static void AddResponseHeaders(HttpResponseHeaders headers)
 {
     headers.Add("x-api-version", _versionNumber);
     headers.Add("x-api-build", _buildNumber);
 }
 public static string GetFirstValue(this HttpResponseHeaders headers, string key)
 {
     return(headers.First(x => x.Key.ToLower() == key.ToLower()).Value.First());
 }
Beispiel #31
0
 /// <summary>Initializes a new instance of the <see cref="StripeResponse"/> class.</summary>
 /// <param name="statusCode">The HTTP status code.</param>
 /// <param name="headers">The HTTP headers of the response.</param>
 /// <param name="content">The body of the response.</param>
 public StripeResponse(HttpStatusCode statusCode, HttpResponseHeaders headers, string content)
 {
     this.StatusCode = statusCode;
     this.Headers    = headers;
     this.Content    = content;
 }
        public static string GetFirstValueOrNull(this HttpResponseHeaders headers, string key)
        {
            var header = headers.FirstOrDefault(x => x.Key == key);

            return(header.Key == null ? null : header.Value.FirstOrDefault());
        }