コード例 #1
0
        public void ContentLocation_ReadAndWriteProperty_ValueMatchesPriorSetValue()
        {
            Assert.Null(_headers.ContentLocation);

            Uri expected = new Uri("http://example.com/path/");

            _headers.ContentLocation = expected;
            Assert.Equal(expected, _headers.ContentLocation);

            _headers.ContentLocation = null;
            Assert.Null(_headers.ContentLocation);
            Assert.False(_headers.Contains("Content-Location"));
        }
コード例 #2
0
        private static void SetContentHeaders(HttpWebRequest webRequest, HttpRequestMessage request)
        {
            if (request.Content != null)
            {
                HttpContentHeaders headers = request.Content.Headers;

                // All content headers besides Content-Length can be added directly to HWR. So just check whether we
                // have the Content-Length header set. If not, add all headers, otherwise skip the Content-Length
                // header.
                // Note that this method is called _before_ PrepareWebRequestForContentUpload(): I.e. in most scenarios
                // this means that no one accessed Headers.ContentLength property yet, thus there will be no
                // Content-Length header in the store. I.e. we'll end up in the 'else' block providing better perf,
                // since no string comparison is required.
                if (headers.Contains(HttpKnownHeaderNames.ContentLength))
                {
                    foreach (var header in request.Content.Headers)
                    {
                        if (string.Compare(HttpKnownHeaderNames.ContentLength, header.Key, StringComparison.OrdinalIgnoreCase) != 0)
                        {
                            // Use AddInternal() to skip validation.
                            webRequest.Headers.AddInternal(header.Key, string.Join(", ", header.Value));
                        }
                    }
                }
                else
                {
                    foreach (var header in request.Content.Headers)
                    {
                        // Use AddInternal() to skip validation.
                        webRequest.Headers.AddInternal(header.Key, string.Join(", ", header.Value));
                    }
                }
            }
        }
コード例 #3
0
		public static void AssertValidHeaders(HttpHeaders messageHeaders, HttpContentHeaders contentHeaders)
		{
			if (messageHeaders != null && messageHeaders.Contains("Transfer-Encoding"))
			{
				if (contentHeaders != null && contentHeaders.Contains("Content-Length"))
				{
					contentHeaders.Remove("Content-Length");
				}
			}
			// Any Content-Length field value greater than or equal to zero is valid.
			if (contentHeaders != null && contentHeaders.Contains("Content-Length"))
			{
				if (contentHeaders.ContentLength < 0)
					throw new HttpRequestException("Content-Length MUST be larger than zero.");
			}
		}
コード例 #4
0
 public static void Set(this HttpContentHeaders headers, string name, string value)
 {
     if (headers.Contains(name))
     {
         headers.Remove(name);
     }
     headers.Add(name, value);
 }
コード例 #5
0
        public static void Set(this HttpContentHeaders headers, string name, IEnumerable <string> values)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            if (headers.Contains(name))
            {
                headers.Remove(name);
            }

            headers.Add(name, values);
        }
コード例 #6
0
        /// <summary>
        /// Add a name value pair to the headers. If the name already exists then the
        /// value will be updated.
        /// </summary>
        /// <param name="source">Headers collection to perform the operation on.</param>
        /// <param name="name">The header to add or update in the collection.</param>
        /// <param name="value">The content of the header.</param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="source" /> is null.</exception>
        public static void AddOrUpdate(this HttpContentHeaders source, string name, string value)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (source.Contains(name))
            {
                source.Remove(name);
            }

            source.Add(name, value);
        }
コード例 #7
0
 private static void AssertActualHeaders(HttpContentHeaders headers, SoapVersion soapVersion, string action)
 {
     if (headers.Contains("ActionHeader"))
     {
         soapVersion.Should().Be(SoapVersion.Soap11);
         headers.GetValues("ActionHeader").Single().Should().Be(action);
     }
     else if (headers.ContentType.Parameters.Any(e => e.Name == "ActionParameter"))
     {
         var actionParam = headers.ContentType.Parameters.Single(e => e.Name == "ActionParameter");
         actionParam.Value.Should().Be($"\"{action}\"");
         soapVersion.Should().Be(SoapVersion.Soap12);
     }
 }
コード例 #8
0
        public void ContentLength_SetCustomValue_TryComputeLengthNotInvoked()
        {
            _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => { throw new ShouldNotBeInvokedException(); }));

            _headers.ContentLength = 27;
            Assert.Equal((long)27, _headers.ContentLength);
            Assert.Equal((long)27, _headers.GetSingleParsedValue(KnownHeaders.ContentLength.Descriptor));

            // After explicitly setting the content length, set it to null.
            _headers.ContentLength = null;
            Assert.Null(_headers.ContentLength);
            Assert.False(_headers.Contains(KnownHeaders.ContentLength.Name));

            // Make sure the header gets serialized correctly
            _headers.ContentLength = 12345;
            Assert.Equal("12345", _headers.GetValues("Content-Length").First());
        }
コード例 #9
0
        public void ContentLength_SetCustomValue_DelegateNotInvoked()
        {
            _headers = new HttpContentHeaders(() => { throw new ShouldNotBeInvokedException(); });

            _headers.ContentLength = 27;
            Assert.Equal((long)27, _headers.ContentLength);
            Assert.Equal((long)27, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength));

            // After explicitly setting the content length, set it to null.
            _headers.ContentLength = null;
            Assert.Equal(null, _headers.ContentLength);
            Assert.False(_headers.Contains(HttpKnownHeaderNames.ContentLength));

            // Make sure the header gets serialized correctly
            _headers.ContentLength = 12345;
            Assert.Equal("12345", _headers.GetValues("Content-Length").First());
        }
コード例 #10
0
        public void ContentLength_ReadValue_TryComputeLengthInvoked()
        {
            _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => 15));

            // The delegate is invoked to return the length.
            Assert.Equal(15, _headers.ContentLength);
            Assert.Equal((long)15, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor));

            // After getting the calculated content length, set it to null.
            _headers.ContentLength = null;
            Assert.Equal(null, _headers.ContentLength);
            Assert.False(_headers.Contains(KnownHeaders.ContentLength.Name));

            _headers.ContentLength = 27;
            Assert.Equal((long)27, _headers.ContentLength);
            Assert.Equal((long)27, _headers.GetParsedValues(KnownHeaders.ContentLength.Descriptor));
        }
コード例 #11
0
        public void ContentLength_ReadValue_DelegateInvoked()
        {
            _headers = new HttpContentHeaders(() => { return(15); });

            // The delegate is invoked to return the length.
            Assert.Equal(15, _headers.ContentLength);
            Assert.Equal((long)15, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength));

            // After getting the calculated content length, set it to null.
            _headers.ContentLength = null;
            Assert.Equal(null, _headers.ContentLength);
            Assert.False(_headers.Contains(HttpKnownHeaderNames.ContentLength));

            _headers.ContentLength = 27;
            Assert.Equal((long)27, _headers.ContentLength);
            Assert.Equal((long)27, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength));
        }
コード例 #12
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);
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageByteArray" /> class.
        /// </summary>
        /// <param name="imageData">The image data byte array.</param>
        /// <param name="headers">The response headers.</param>
        public ImageByteArray(byte[] imageData, HttpContentHeaders headers)
        {
            Bytes = imageData;
            if (headers == null)
            {
                return;
            }

            // Attempt to set the ImageTime property.
            if (headers.Contains("Image-Time"))
            {
                try
                {
                    var imageTimeHeaderValues = headers.GetValues("Image-Time");
                    if (imageTimeHeaderValues != null)
                    {
                        var imageTimeHeaderValue = imageTimeHeaderValues.FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(imageTimeHeaderValue))
                        {
                            DateTime parsedTime;
                            if (DateTime.TryParse(imageTimeHeaderValue, out parsedTime))
                            {
                                ImageTime = parsedTime.ToUniversalTime();
                            }
                            else
                            {
                                MainForm.Instance.WriteToLog("Failed to parse Image-Time header field.");
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    MainForm.Instance.WriteToLog("Failed to set the image time.");
                }
            }

            if (headers.ContentType != null)
            {
                ContentType = headers.ContentType.MediaType;
            }
        }
        /// <summary>Copies all headers from the source to the target.</summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="handleContentLength">true to handle content length.</param>
        /// <param name="handleContentEncoding">true to handle content encoding.</param>
        /// <param name="handleChangedValues">true to handle changed values.</param>
        public static void CopyTo(
            this HttpContentHeaders source,
            HttpContentHeaders target,
            bool handleContentLength   = true,
            bool handleContentEncoding = true,
            bool handleChangedValues   = false)
        {
            // Remove headers we are going to rewrite and headers with null values
            foreach (var header in source)
            {
                try
                {
                    if (!handleContentLength && header.Key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }

                    if (!handleContentEncoding && header.Key.Equals("Content-Encoding", StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }

                    if (!handleChangedValues)
                    {
                        // If values have changed, dont update it
                        if (target.Contains(header.Key))
                        {
                            if (target.GetValues(header.Key).Any(targetValue => header.Value.Any(originalValue => originalValue != targetValue)))
                            {
                                return;
                            }
                        }
                    }

                    target.Add(header.Key, header.Value);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
        }
コード例 #15
0
        public static HttpClient GetClient(string authenticationToken, HttpContentHeaders headers = null)
        {
            if (headers == null || !headers.Contains("ContentType"))
            {
                Client.DefaultRequestHeaders.Add("ContentType", "application/json");
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    Client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            if (!Client.DefaultRequestHeaders.Contains("BAuth"))
            {
                Client.DefaultRequestHeaders.Add("BAuth", "Basic " + authenticationToken);
            }

            return(Client);
        }
コード例 #16
0
        public static HttpClient GetClient(HttpContentHeaders headers = null)
        {
            if (headers == null || !headers.Contains("ContentType"))
            {
                Client.DefaultRequestHeaders.Add("ContentType", "application/json");
            }

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    Client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            if (Client.DefaultRequestHeaders.Contains("BAuth"))
            {
                Client.DefaultRequestHeaders.Authorization = null;
            }

            return(Client);
        }
        /// <summary>Copies all headers from the source to the target.</summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <param name="handleContentLength">true to handle content length.</param>
        /// <param name="handleChangedValues">true to handle changed values.</param>
        public static void CopyTo(
            this HttpContentHeaders source,
            HttpContentHeaders target,
            bool handleContentLength = true,
            bool handleChangedValues = false)
        {
            // Copy all other headers unless they have been modified and we want to preserve that
            foreach (var header in source)
            {
                try
                {
                    if (!handleContentLength && header.Key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    if (!handleChangedValues)
                    {
                        // If values have changed, dont update it
                        if (target.Contains(header.Key))
                        {
                            if (target.GetValues(header.Key).Any(targetValue => header.Value.Any(originalValue => originalValue != targetValue)))
                            {
                                continue;
                            }
                        }
                    }

                    target.Add(header.Key, header.Value);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }
        }
コード例 #18
0
        /**************************************************************************/

        private void ProcessResponseHttpHeaders(MacroscopeHttpTwoClientResponse Response)
        {
            HttpResponseMessage ResponseMessage = Response.GetResponse();
            HttpResponseHeaders ResponseHeaders = ResponseMessage.Headers;
            HttpContentHeaders  ContentHeaders  = ResponseMessage.Content.Headers;

            /** Status Code ------------------------------------------------------ **/

            this.SetStatusCode(ResponseMessage.StatusCode);

            this.SetErrorCondition(ResponseMessage.ReasonPhrase);

            try
            {
                switch (this.GetStatusCode())
                {
                // 200 Range

                case HttpStatusCode.OK:
                    this.SetIsNotRedirect();
                    break;

                // 300 Range

                case HttpStatusCode.Moved:
                    this.SetErrorCondition(HttpStatusCode.Moved.ToString());
                    this.SetIsRedirect();
                    break;

                case HttpStatusCode.SeeOther:
                    this.SetErrorCondition(HttpStatusCode.SeeOther.ToString());
                    this.SetIsRedirect();
                    break;

                case HttpStatusCode.Found:
                    this.SetErrorCondition(HttpStatusCode.Redirect.ToString());
                    this.SetIsRedirect();
                    break;

                // 400 Range

                case HttpStatusCode.BadRequest:
                    this.SetErrorCondition(HttpStatusCode.BadRequest.ToString());
                    this.SetIsNotRedirect();
                    break;

                case HttpStatusCode.Unauthorized:
                    this.SetErrorCondition(HttpStatusCode.Unauthorized.ToString());
                    this.SetIsNotRedirect();
                    break;

                case HttpStatusCode.PaymentRequired:
                    this.SetErrorCondition(HttpStatusCode.PaymentRequired.ToString());
                    this.SetIsNotRedirect();
                    break;

                case HttpStatusCode.Forbidden:
                    this.SetErrorCondition(HttpStatusCode.Forbidden.ToString());
                    this.SetIsNotRedirect();
                    break;

                case HttpStatusCode.NotFound:
                    this.SetErrorCondition(HttpStatusCode.NotFound.ToString());
                    this.SetIsNotRedirect();
                    break;

                case HttpStatusCode.MethodNotAllowed:
                    this.SetErrorCondition(HttpStatusCode.MethodNotAllowed.ToString());
                    this.SetIsNotRedirect();
                    break;

                case HttpStatusCode.Gone:
                    this.SetErrorCondition(HttpStatusCode.Gone.ToString());
                    this.SetIsNotRedirect();
                    break;

                case HttpStatusCode.RequestUriTooLong:
                    this.SetErrorCondition(HttpStatusCode.RequestUriTooLong.ToString());
                    this.SetIsNotRedirect();
                    break;

                // Unhandled

                default:
                    throw new MacroscopeDocumentException("Unhandled HttpStatusCode Type");
                }
            }
            catch (MacroscopeDocumentException ex)
            {
                this.DebugMsg(string.Format("MacroscopeDocumentException: {0}", ex.Message));
            }

            /** Raw HTTP Headers ------------------------------------------------- **/

            this.SetHttpResponseStatusLine(Response: Response);

            this.SetHttpResponseHeaders(Response: Response);

            /** Server Information ----------------------------------------------- **/

            /*{
             * this.ServerName = ResponseHeaders.Server.First().ToString();
             * }*/

            /** PROBE HTTP HEADERS ----------------------------------------------- **/

            /** Server HTTP Header ----------------------------------------------- **/
            try
            {
                HttpHeaderValueCollection <ProductInfoHeaderValue> HeaderValue = ResponseHeaders.Server;
                if (HeaderValue != null)
                {
                    if (HeaderValue.FirstOrDefault() != null)
                    {
                        this.SetServerName(HeaderValue.FirstOrDefault().ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.SetServerName(HeaderValues.First().ToString());
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "server", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "server", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.ServerName: {0}", this.ServerName));

            /** Content-Type HTTP Header ----------------------------------------- **/
            try
            {
                MediaTypeHeaderValue HeaderValue = ContentHeaders.ContentType;
                if (HeaderValue != null)
                {
                    this.DebugMsg(string.Format("HeaderValue: {0}", HeaderValue));
                    this.MimeType = HeaderValue.MediaType;
                    if (HeaderValue.CharSet != null)
                    {
                        this.SetCharacterSet(HeaderValue.CharSet);
                        // TODO: Implement character set probing
                        this.SetCharacterEncoding(NewEncoding: new UTF8Encoding());
                    }
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(string.Format("MediaType Exception: {0}", ex.Message));
                this.MimeType = MacroscopeConstants.DefaultMimeType;
            }

            this.DebugMsg(string.Format("this.MimeType: {0}", this.MimeType));

            /** Content-Length HTTP Header --------------------------------------- **/
            try
            {
                long?HeaderValue = null;
                if (ContentHeaders.Contains("Content-Length"))
                {
                    HeaderValue = ContentHeaders.ContentLength;
                }
                if (HeaderValue != null)
                {
                    this.ContentLength = HeaderValue;
                }
                else
                {
                    this.ContentLength = 0;
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                this.SetContentLength(Length: 0);
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.SetContentLength(Length: long.Parse(HeaderValues.FirstOrDefault()));
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "content-length", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "content-length", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.GetContentLength(): {0}", this.GetContentLength()));

            /** Content-Encoding HTTP Header ------------------------------------- **/
            try
            {
                ICollection <string> HeaderValue = ContentHeaders.ContentEncoding;
                if (HeaderValue != null)
                {
                    this.ContentEncoding = HeaderValue.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.ContentEncoding = HeaderValues.FirstOrDefault();
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "content-encoding", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "content-encoding", Callback: Callback);
                }
            }

            if (string.IsNullOrEmpty(this.CompressionMethod) && (!string.IsNullOrEmpty(this.ContentEncoding)))
            {
                this.IsCompressed      = true;
                this.CompressionMethod = this.ContentEncoding;
            }

            this.DebugMsg(string.Format("this.ContentEncoding: {0}", this.ContentEncoding));
            this.DebugMsg(string.Format("this.CompressionMethod: {0}", this.CompressionMethod));

            /** Date HTTP Header ------------------------------------------------- **/
            try
            {
                DateTimeOffset?HeaderValue = ResponseHeaders.Date;
                if (HeaderValue != null)
                {
                    this.DateServer = MacroscopeDateTools.ParseHttpDate(DateString: HeaderValue.ToString());
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                this.DateServer = new DateTime();
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.DateServer = MacroscopeDateTools.ParseHttpDate(DateString: HeaderValues.First().ToString());
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "date", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "date", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.DateServer: {0}", this.DateServer));

            /** Last-Modified HTTP Header ---------------------------------------- **/
            try
            {
                DateTimeOffset?HeaderValue = ContentHeaders.LastModified;
                if (HeaderValue != null)
                {
                    this.DateModified = MacroscopeDateTools.ParseHttpDate(DateString: HeaderValue.ToString());
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                this.DateModified = new DateTime();
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.DateModified = MacroscopeDateTools.ParseHttpDate(DateString: HeaderValues.First().ToString());
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "last-modified", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "last-modified", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.DateModified: {0}", this.DateModified));

            /** Expires HTTP Header ---------------------------------------------- **/
            try
            {
                DateTimeOffset?HeaderValue = ContentHeaders.Expires;
                if (HeaderValue != null)
                {
                    this.DateExpires = MacroscopeDateTools.ParseHttpDate(DateString: HeaderValue.ToString());
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                this.DateExpires = new DateTime();
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.DateExpires = MacroscopeDateTools.ParseHttpDate(DateString: HeaderValues.First().ToString());
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "expires", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "expires", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.DateExpires: {0}", this.DateExpires));

            /** HTST Policy HTTP Header ------------------------------------------ **/
            // https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet
            // Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
            {
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.HypertextStrictTransportPolicy = true;
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "strict-transport-security", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "strict-transport-security", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.HypertextStrictTransportPolicy: {0}", this.HypertextStrictTransportPolicy));

            /** Location (Redirect) HTTP Header ---------------------------------- **/
            try
            {
                Uri HeaderValue = ResponseHeaders.Location;
                if (HeaderValue != null)
                {
                    this.SetUrlRedirectTo(Url: HeaderValue.ToString());
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    this.SetUrlRedirectTo(Url: HeaderValues.FirstOrDefault().ToString());
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "location", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "location", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.GetIsRedirect(): {0}", this.GetIsRedirect()));
            this.DebugMsg(string.Format("this.GetUrlRedirectTo(): {0}", this.GetUrlRedirectTo()));

            /** Link HTTP Headers ------------------------------------------------ **/
            {
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    foreach (string HeaderValue in HeaderValues)
                    {
                        this.DebugMsg(string.Format("HeaderValue: {0}", HeaderValue));
                        this.ProcessHttpLinkHeader(HttpLinkHeader: HeaderValue);
                    }
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "link", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "link", Callback: Callback);
                }
            }

            /** ETag HTTP Header ------------------------------------------------- **/
            try
            {
                EntityTagHeaderValue HeaderValue = ResponseHeaders.ETag;
                if (HeaderValue != null)
                {
                    string ETagValue = HeaderValue.Tag;
                    if (!string.IsNullOrEmpty(ETagValue))
                    {
                        this.SetEtag(HeaderValue.Tag);
                    }
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
                FindHttpResponseHeaderCallback Callback = delegate(IEnumerable <string> HeaderValues)
                {
                    string HeaderValue = HeaderValues.FirstOrDefault();
                    if (HeaderValue != null)
                    {
                        if (!string.IsNullOrEmpty(HeaderValue))
                        {
                            this.SetEtag(HeaderValue);
                        }
                    }
                    return(true);
                };
                if (!this.FindHttpResponseHeader(ResponseHeaders: ResponseHeaders, HeaderName: "etag", Callback: Callback))
                {
                    this.FindHttpContentHeader(ContentHeaders: ContentHeaders, HeaderName: "etag", Callback: Callback);
                }
            }

            this.DebugMsg(string.Format("this.Etag: {0}", this.Etag));

            /** WWW-AUTHENTICATE HTTP Header ------------------------------------- **/
            // Reference: http://httpbin.org/basic-auth/user/passwd
            try
            {
                HttpHeaderValueCollection <AuthenticationHeaderValue> HeaderValue = ResponseHeaders.WwwAuthenticate;
                if (HeaderValue != null)
                {
                    string Scheme = null;
                    string Realm  = null;
                    foreach (AuthenticationHeaderValue AuthenticationValue in HeaderValue)
                    {
                        Scheme = AuthenticationValue.Scheme;
                        string Parameter = AuthenticationValue.Parameter;
                        Match  Matched   = Regex.Match(Parameter, "^[^\"]+\"([^\"]+)\"");
                        if (Matched.Success)
                        {
                            Realm = Matched.Groups[1].Value;
                        }
                    }
                    if (!string.IsNullOrEmpty(Scheme) && !string.IsNullOrEmpty(Realm))
                    {
                        if (Scheme.ToLower() == "basic")
                        {
                            this.SetAuthenticationType(MacroscopeConstants.AuthenticationType.BASIC);
                            this.SetAuthenticationRealm(Realm);
                        }
                        else
                        {
                            this.SetAuthenticationType(MacroscopeConstants.AuthenticationType.UNSUPPORTED);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.DebugMsg(ex.Message);
            }
            this.DebugMsg(string.Format("WwwAuthenticate: \"{0}\", Realm: \"{1}\"", this.GetAuthenticationType(), this.GetAuthenticationRealm()));

            /** Process Dates ---------------------------------------------------- **/
            {
                if (this.DateServer.Date == new DateTime().Date)
                {
                    this.DateServer = DateTime.UtcNow;
                }
                if (this.DateModified.Date == new DateTime().Date)
                {
                    this.DateModified = this.DateServer;
                }
            }

            /** Process MIME Type ------------------------------------------------ **/
            {
                Regex reIsHtml       = new Regex(@"^(text/html|application/xhtml+xml)", RegexOptions.IgnoreCase);
                Regex reIsCss        = new Regex(@"^text/css", RegexOptions.IgnoreCase);
                Regex reIsJavascript = new Regex(@"^(application/javascript|text/javascript)", RegexOptions.IgnoreCase);
                Regex reIsImage      = new Regex(@"^image/(gif|png|jpeg|bmp|webp|vnd.microsoft.icon|x-icon)", RegexOptions.IgnoreCase);
                Regex reIsPdf        = new Regex(@"^application/pdf", RegexOptions.IgnoreCase);
                Regex reIsAudio      = new Regex(@"^audio/[a-z0-9]+", RegexOptions.IgnoreCase);
                Regex reIsVideo      = new Regex(@"^video/[a-z0-9]+", RegexOptions.IgnoreCase);
                Regex reIsXml        = new Regex(@"^(application|text)/(atom\+xml|xml)", RegexOptions.IgnoreCase);
                Regex reIsText       = new Regex(@"^(text)/(plain)", RegexOptions.IgnoreCase);

                if (reIsHtml.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.HTML);
                }
                else
                if (reIsCss.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.CSS);
                }
                else
                if (reIsJavascript.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.JAVASCRIPT);
                }
                else
                if (reIsImage.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.IMAGE);
                }
                else
                if (reIsPdf.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.PDF);
                }
                else
                if (reIsAudio.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.AUDIO);
                }
                else
                if (reIsVideo.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.VIDEO);
                }
                else
                if (reIsXml.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.XML);
                }
                else
                if (reIsText.IsMatch(this.MimeType))
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.TEXT);
                }
                else
                {
                    this.SetDocumentType(Type: MacroscopeConstants.DocumentType.BINARY);
                }
            }

            /** Process Cookies -------------------------------------------------- **/
            // https://stackoverflow.com/questions/29224734/how-to-read-cookies-from-httpresponsemessage
            {
                try
                {
                    CookieContainer  CookieMonster = MacroscopeHttpTwoClient.GetCookieMonster();
                    CookieCollection Biscuits      = CookieMonster.GetCookies(uri: this.GetUri());
                    this.AddCookies(Cookies: Biscuits);
                    this.DebugMsg("cookies");


//          CookieContainer CookieTin = MacroscopeHttpTwoClient.GetCookieMonster();
//          string LimpBizkit = tin.GetCookieHeader( uri: Request.RequestUri );
                }
                catch (Exception ex)
                {
                    this.DebugMsg(ex.Message);
                }
            }

            return;
        }
コード例 #19
0
 public static string Get(this HttpContentHeaders headers, string name)
 {
     return(headers.Contains(name) ? headers.GetValues(name).FirstOrDefault() : null);
 }