Headers

Namespace: Suave
We found 10 examples in language CSharp for this search. You will see 46 fragments of code.

Other methods

Other methods

        [Test]
        public void SetItem_SetsItem()
        {
            var headers = new Headers
            {
                ["key"] = "value"
            };

            headers.Single().ShouldBe(new KeyValuePair<string, string>("key", "value"));
        }

        [Test]
        public void SetItem_Throws_WhenKeyNull()
        {
            Action action = () => new Headers { [null] = "value" };

            action.ShouldThrow<ArgumentNullException>()
                .ParamName.ShouldBe("name");
        }

        [Test]
        public void SetItem_Throws_WhenKeyEmpty()
        {
            ArgumentException exception = null;
            Action action = () => new Headers { [""] = "a" };

            action.ShouldSatisfyAllConditions(
                () => exception = action.ShouldThrow<ArgumentException>(),
                () => exception.Message.ShouldStartWith(SR.Format(SR.ApiHeaderNameIsEmpty)),
                () => exception.ParamName.ShouldBe("name")
            );
        }

        [Test]
        public void SetItem_SetsMultipleItems_WhenSameKey()
        {
            var headers = new Headers
            {
                ["key"] = "value",
                ["key"] = "two"
            };

            headers.ToArray().ShouldBe(new[] {
                new KeyValuePair<string, string>("key", "value"),
                new KeyValuePair<string, string>("key", "two")
            });
        }

        [Test]
        public void SetItem_ClearsMultipleItems_WhenSameKeyAndValueNull()
        {
            var headers = new Headers
            {
                ["one"] = "me",
                ["key"] = "value",
                ["key"] = "two",
                ["key"] = null
            };

            headers.ToArray().ShouldBe(new[] {
                new KeyValuePair<string, string>("one", "me")
            });
        }

        [TestCase("room")]
        [TestCase("tWO")]
        public void GetItem_GetsPreviouslySetItem(string value)
        {
            var headers = new Headers
            {
                ["loc"] = value
            };

            headers["loc"].ShouldBe(value);
        }


        [Fact]
        public void ToResponseHeaders_ReturnsNoHeaders_ByDefault()
        {
            CorsResult result = new CorsResult();

            IDictionary<string, string> headers = result.ToResponseHeaders();

            Assert.Empty(headers);
        }

        [Fact]
        public void ToResponseHeaders_AllowOrigin_AllowOriginHeaderAdded()
        {
            CorsResult result = new CorsResult
            {
                AllowedOrigin = "http://example.com"
            };

            IDictionary<string, string> headers = result.ToResponseHeaders();

            Assert.Equal("http://example.com", headers["Access-Control-Allow-Origin"]);
        }

        [Fact]
        public void ToResponseHeaders_NoAllowOrigin_AllowOriginHeaderNotAdded()
        {
            CorsResult result = new CorsResult
            {
                AllowedOrigin = null
            };

            IDictionary<string, string> headers = result.ToResponseHeaders();

            Assert.DoesNotContain("Access-Control-Allow-Origin", headers.Keys);
        }

        [Fact]
        public void ToResponseHeaders_AllowCredentials_AllowCredentialsHeaderAdded()
        {
            CorsResult result = new CorsResult
            {
                SupportsCredentials = true
            };

            IDictionary<string, string> headers = result.ToResponseHeaders();

            Assert.Equal("true", headers["Access-Control-Allow-Credentials"]);
        }

        [Fact]
        public void ToResponseHeaders_NoAllowCredentials_AllowCredentialsHeaderNotAdded()
        {
            CorsResult result = new CorsResult
            {
                SupportsCredentials = false
            };

            IDictionary<string, string> headers = result.ToResponseHeaders();

            Assert.DoesNotContain("Access-Control-Allow-Credentials", headers.Keys);
        }

        [Fact]
        public void ToResponseHeaders_NoAllowMethods_AllowMethodsHeaderNotAdded()
        {
            CorsResult result = new CorsResult
            {
                // AllowMethods is empty by default
            };

            IDictionary<string, string> headers = result.ToResponseHeaders();

            Assert.DoesNotContain("Access-Control-Allow-Methods", headers.Keys);
        }


        [Fact]
        public void WriteCorsHeaders_EmptyCorsResult_EmptyHeaders()
        {
            HttpResponseMessage response = new HttpResponseMessage();
            response.WriteCorsHeaders(new CorsResult());
            Assert.Empty(response.Headers);
        }


        [Test]
        public void AddLocation_Throws_WhenLocationIsNull()
        {
            Action action = () => new Headers().AddLocation(null);

            action.ShouldThrow<ArgumentNullException>()
                .ParamName.ShouldBe("location");
        }

        [Test]
        public void AddLocation_ReturnsTheSameHeadersInstance()
        {
            var headers = new Headers();

            Headers result = headers.AddLocation(new Uri("https://location.com"));

            result.ShouldBeSameAs(headers);
        }

        [Test]
        public void AddLocation_AddsValidLocationHeader()
        {
            var headers = new Headers();
            var uri = new Uri("https://location.com");

            headers.AddLocation(uri);

            headers["Location"].ShouldBe(uri.AbsoluteUri);
        }

        [TestCase(null)]
        [TestCase("")]
        public void AddWwwAuthenticate_Throws_WhenChallengeIsEmpty(string challenge)
        {
            Action action = () => new Headers().AddWwwAuthenticate(challenge);

            ArgumentException exception = action.ShouldThrow<ArgumentException>();
            exception.ParamName.ShouldBe("challenge");
            exception.Message.ShouldStartWith(SR.Format(SR.ApiHeaderChallengeEmpty));
        }

        [TestCase("simple")]
        [TestCase("bearer")]
        public void AddWwwAuthenticate_AddsValidHeader(string challenge)
        {
            var headers = new Headers();

            headers.AddWwwAuthenticate(challenge);

            headers["WWW-Authenticate"].ShouldBe(challenge);
        }

        [Test]
        public void AddWwwAuthenticate_ReturnsTheSameHeadersInstance()
        {
            var headers = new Headers();

            Headers result = headers.AddWwwAuthenticate("a");

            result.ShouldBeSameAs(headers);
        }


		[Test]
		public void Headers_Request ()
		{
			HttpResponseMessage message = new HttpResponseMessage ();
			HttpResponseHeaders headers = message.Headers;

			headers.Add ("accept", "audio");
			Assert.AreEqual ("audio", headers.GetValues ("Accept").First (), "#1");

			headers.Clear ();
			Assert.IsTrue (headers.TryAddWithoutValidation ("accept", "audio"), "#2a");
			Assert.AreEqual ("audio", headers.GetValues ("Accept").First (), "#2");
		}

		[Test]
		public void Headers_Location ()
		{
			HttpResponseMessage message = new HttpResponseMessage ();
			HttpResponseHeaders headers = message.Headers;
			headers.TryAddWithoutValidation ("location", "http://w3.org");
			Assert.AreEqual (new Uri ("http://w3.org"), headers.Location);
		}

		[Test]
		public void Headers_TransferEncoding ()
		{
			HttpResponseMessage message = new HttpResponseMessage ();
			HttpResponseHeaders headers = message.Headers;
			headers.TryAddWithoutValidation ("Transfer-Encoding", "mmm");
			headers.TryAddWithoutValidation ("Transfer-Encoding", "▀");
			headers.TryAddWithoutValidation ("Transfer-Encoding", "zz");

			var a = headers.TransferEncoding;
			Assert.AreEqual (2, a.Count, "#1");

			// Assert.AreEqual ("mmm, zz, ▀", a.ToString (), "#2");
		}


		[Test]
		public void Ctor_Default ()
		{
			var m = new HttpRequestMessage ();
			Assert.IsNull (m.Content, "#1");
			Assert.IsNotNull (m.Headers, "#2");
			Assert.AreEqual (HttpMethod.Get, m.Method, "#3");
			Assert.IsNotNull (m.Properties, "#4");
			Assert.IsNull (m.RequestUri, "#5");
			Assert.AreEqual (new Version (1, 1), m.Version, "#6");

			Assert.AreEqual ("Method: GET, RequestUri: '<null>', Version: 1.1, Content: <null>, Headers:\r\n{\r\n}", m.ToString (), "#7");
		}

		[Test]
		public void Headers_From_Invalid ()
		{
			HttpRequestMessage message = new HttpRequestMessage ();
			HttpRequestHeaders headers = message.Headers;
			headers.From = null;
			headers.From = "";
			try {
				headers.From = " ";
				Assert.Fail ("#1");
			} catch (FormatException) {
			}
			try {
				headers.From = "test";
				Assert.Fail ("#2");
			} catch (FormatException) {
			}
		}


        [Fact]
        public void Location_UseAddMethodWithInvalidValue_InvalidValueRecognized()
        {
            headers.TryAddWithoutValidation("Location", " http://example.com http://other");
            Assert.Null(headers.GetParsedValues(KnownHeaders.Location.Descriptor));
            Assert.Equal(1, headers.GetValues("Location").Count());
            Assert.Equal(" http://example.com http://other", headers.GetValues("Location").First());
        }

        [Fact]
        public void ETag_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
        {
            headers.TryAddWithoutValidation("ETag", "W/\"tag\"");
            Assert.Equal(new EntityTagHeaderValue("\"tag\"", true), headers.ETag);
        }

        [Fact]
        public void AcceptRanges_AddInvalidValue_Throw()
        {
            Assert.Throws<FormatException>(() => { headers.AcceptRanges.Add("this is invalid"); });
        }

        [Fact]
        public void AcceptRanges_UseAddMethodWithInvalidValue_InvalidValueRecognized()
        {
            headers.TryAddWithoutValidation("Accept-Ranges", "custom1 custom2"); // no separator

            Assert.Equal(0, headers.AcceptRanges.Count);
            Assert.Equal(1, headers.GetValues("Accept-Ranges").Count());
            Assert.Equal("custom1 custom2", headers.GetValues("Accept-Ranges").First());
        }

        [Fact]
        public void RetryAfter_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
        {
            headers.TryAddWithoutValidation("Retry-After", " 2100000 ");
            Assert.Equal(new RetryConditionHeaderValue(new TimeSpan(0, 0, 2100000)), headers.RetryAfter);
        }

        [Fact]
        public void Vary_UseAddMethodWithInvalidValue_InvalidValueRecognized()
        {
            headers.TryAddWithoutValidation("Vary", "custom1 custom2"); // no separator

            Assert.Equal(0, headers.Vary.Count);
            Assert.Equal(1, headers.GetValues("Vary").Count());
            Assert.Equal("custom1 custom2", headers.GetValues("Vary").First());
        }



        [Fact]
        public void HeaderParserNullBuffer()
        {
            HttpHeaders headers;
            InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(128, out headers);
            Assert.NotNull(parser);
            int bytesConsumed = 0;
            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed); }, "buffer");
        }

        private static IEnumerable<HttpHeaders> CreateHttpHeaders()
        {
            return new HttpHeaders[]
            {
                new HttpRequestMessage().Headers,
                new HttpResponseMessage().Headers,
                new StringContent(String.Empty).Headers,
            };
        }

        private static InternetMessageFormatHeaderParser CreateHeaderParser(int maximumHeaderLength, out HttpHeaders headers)
        {
            headers = new HttpRequestMessage().Headers;
            return new InternetMessageFormatHeaderParser(headers, maximumHeaderLength);
        }

        internal static byte[] CreateBuffer(params string[] headers)
        {
            const string CRLF = "\r\n";
            StringBuilder header = new StringBuilder();
            foreach (var h in headers)
            {
                header.Append(h + CRLF);
            }

            header.Append(CRLF);
            return Encoding.UTF8.GetBytes(header.ToString());
        }


        [Theory]
        [InlineData(null)]
        [InlineData("")]
        public void TryAddWithoutValidation_UseEmptyHeaderName_False(string headerName)
        {
            MockHeaders headers = new MockHeaders();
            Assert.False(headers.TryAddWithoutValidation(headerName, "value"));
        }

        [Theory]
        [MemberData(nameof(GetInvalidHeaderNames))]
        public void TryAddWithoutValidation_UseInvalidHeaderName_False(string headerName)
        {
            MockHeaders headers = new MockHeaders();

            Assert.False(headers.TryAddWithoutValidation(headerName, "value"));
        }

        [Fact]
        public void TryAddWithoutValidation_AddSingleValue_ValueParsed()
        {
            MockHeaders headers = new MockHeaders();
            headers.TryAddWithoutValidation(headers.Descriptor, rawPrefix);

            Assert.Equal(1, headers.Count());
            Assert.Equal(1, headers.First().Value.Count());
            Assert.Equal(parsedPrefix, headers.First().Value.First());

            Assert.Equal(1, headers.Parser.TryParseValueCallCount);
        }

        [Fact]
        public void TryAddWithoutValidation_MultipleAddNullValueCollection_Throws()
        {
            MockHeaders headers = new MockHeaders();
            string[] values = null;
            
            Assert.Throws<ArgumentNullException>(() => { headers.TryAddWithoutValidation(headers.Descriptor, values); });
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        public void Add_SingleUseEmptyHeaderName_Throw(string headerName)
        {
            MockHeaders headers = new MockHeaders();
            
            AssertExtensions.Throws<ArgumentException>("name", () => { headers.Add(headerName, "value"); });
        }

        [Theory]
        [MemberData(nameof(GetInvalidHeaderNames))]
        public void Add_SingleUseInvalidHeaderName_Throw(string headerName)
        {
            MockHeaders headers = new MockHeaders();

            Assert.Throws<FormatException>(() => { headers.Add(headerName, "value"); });
        }


        #region Request headers

        [Fact]
        public void Accept_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison()
        {
            // Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison.
            Assert.Throws<FormatException>(() => { headers.Add("AcCePt", "this is invalid"); });
        }

        [Fact]
        public void AcceptCharset_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
        {
            headers.TryAddWithoutValidation("Accept-Charset", ", ,,iso-8859-5 , \r\n utf-8 ; q=0.300 ,,,");

            Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"),
                headers.AcceptCharset.ElementAt(0));
            Assert.Equal(new StringWithQualityHeaderValue("utf-8", 0.3),
                headers.AcceptCharset.ElementAt(1));
        }

        [Fact]
        public void Expect_Add100Continue_Success()
        {
            // use non-default casing to make sure we do case-insensitive comparison.
            headers.Expect.Add(new NameValueWithParametersHeaderValue("100-CONTINUE"));
            Assert.True(headers.ExpectContinue == true);
            Assert.Equal(1, headers.Expect.Count);
        }

        [Fact]
        public void Expect_UseAddMethodWithInvalidValue_InvalidValueRecognized()
        {
            headers.TryAddWithoutValidation("Expect", "100-continue other"); // no separator

            Assert.Equal(0, headers.Expect.Count);
            Assert.Equal(1, headers.GetValues("Expect").Count());
            Assert.Equal("100-continue other", headers.GetValues("Expect").First());
        }

        [Fact]
        public void Host_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
        {
            headers.TryAddWithoutValidation("Host", "host:80");

            Assert.Equal("host:80", headers.Host);
        }

        [Fact]
        public void IfMatch_UseAddMethodWithInvalidInput_PropertyNotUpdated()
        {
            headers.TryAddWithoutValidation("If-Match", "W/\"tag1\" \"tag2\""); // no separator
            Assert.Equal(0, headers.IfMatch.Count);
            Assert.Equal(1, headers.GetValues("If-Match").Count());
        }

Suave.Headers : Object

Methods :

public static FSharpOption<DateTime> parseDateTime(String s = )
public static FSharpOption<Decimal> parseDecimal(String s = )
public static FSharpFunc<String, FSharpOption<CultureInfo>> get_parseCultureInfo()
public static FSharpOption<String> getFirstHeader(String name = , HttpContext ctx = )
public static IEnumerable<String> getHeader(String name = , HttpContext ctx = )
public static IDictionary<String, IEnumerable<String>> getHeaders(HttpContext ctx = )
public static IEnumerable<String> getSplitValues(IEnumerable<String> headers = )
public static IEnumerable<Tuple<String, Decimal>> getWeightedValues(IEnumerable<String> splitValues = )
public static FSharpChoice<FSharpList<String>, String> getAll(FSharpList<Tuple<StringString>> target = , String key = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods