public void GetT_UnknownTypeWithTryParseAndMissingValue_Null()
        {
            var headers = new HeaderDictionary();

            var result = headers.Get<TestHeaderValue>("custom");
            Assert.Null(result);
        }
        public void GetT_UnknownTypeWithoutTryParse_Throws()
        {
            var headers = new HeaderDictionary();
            headers["custom"] = "valid";

            Assert.Throws<NotSupportedException>(() => headers.Get<object>("custom"));
        }
        public void GetT_UnknownTypeWithTryParseAndInvalidValue_Null()
        {
            var headers = new HeaderDictionary();
            headers["custom"] = "invalid";

            var result = headers.Get<TestHeaderValue>("custom");
            Assert.Null(result);
        }
        public void GetT_KnownTypeWithMissingValue_Null()
        {
            var headers = new HeaderDictionary();

            var result = headers.Get<MediaTypeHeaderValue>(HeaderNames.ContentType);

            Assert.Null(result);
        }
        public void GetT_KnownTypeWithInvalidValue_Null()
        {
            var headers = new HeaderDictionary();
            headers[HeaderNames.ContentType] = "invalid";

            var result = headers.Get<MediaTypeHeaderValue>(HeaderNames.ContentType);

            Assert.Null(result);
        }
        public void GetT_KnownTypeWithValidValue_Success()
        {
            var headers = new HeaderDictionary();
            headers[HeaderNames.ContentType] = "text/plain";

            var result = headers.Get<MediaTypeHeaderValue>(HeaderNames.ContentType);

            var expected = new MediaTypeHeaderValue("text/plain");
            Assert.Equal(expected, result);
        }
        public void PropertiesAreAccessible()
        {
            var headers = new HeaderDictionary(
                new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
                {
                    { "Header1", new[] { "Value1" } }
                });

            Assert.Equal(1, headers.Count);
            Assert.Equal<string>(new[] { "Header1" }, headers.Keys);
            Assert.True(headers.ContainsKey("header1"));
            Assert.False(headers.ContainsKey("header2"));
            Assert.Equal("Value1", headers["header1"]);
            Assert.Equal("Value1", headers.Get("header1"));
            Assert.Equal(new[] { "Value1" }, headers.GetValues("header1"));
        }
 private static ActionContext GetActionContext(
     MediaTypeHeaderValue contentType,
     MemoryStream responseStream = null)
 {
     var request = new Mock<HttpRequest>();
     var headers = new HeaderDictionary();
     request.Setup(r => r.ContentType).Returns(contentType.ToString());
     request.SetupGet(r => r.Headers).Returns(headers);
     headers[HeaderNames.AcceptCharset] = contentType.Charset;
     var response = new Mock<HttpResponse>();
     response.SetupGet(f => f.Body).Returns(responseStream ?? new MemoryStream());
     var httpContext = new Mock<HttpContext>();
     httpContext.SetupGet(c => c.Request).Returns(request.Object);
     httpContext.SetupGet(c => c.Response).Returns(response.Object);
     return new ActionContext(httpContext.Object, routeData: null, actionDescriptor: null);
 }
 private static ActionContext GetActionContext(string contentType)
 {
     var request = new Mock<HttpRequest>();
     var headers = new HeaderDictionary(new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase));
     headers["Accept-Charset"] = MediaTypeHeaderValue.Parse(contentType).Charset;
     request.Setup(r => r.ContentType).Returns(contentType);
     request.SetupGet(r => r.Headers).Returns(headers);
     var response = new Mock<HttpResponse>();
     response.SetupGet(f => f.Body).Returns(new MemoryStream());
     var httpContext = new Mock<HttpContext>();
     httpContext.SetupGet(c => c.Request).Returns(request.Object);
     httpContext.SetupGet(c => c.Response).Returns(response.Object);
     return new ActionContext(httpContext.Object, routeData: null, actionDescriptor: null);
 }
        public async Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken)
        {
            if (Form != null)
            {
                return Form;
            }

            if (!HasFormContentType)
            {
                throw new InvalidOperationException("Incorrect Content-Type: " + _request.ContentType);
            }

            cancellationToken.ThrowIfCancellationRequested();

            _request.EnableRewind();

            IDictionary<string, string[]> formFields = null;
            var files = new FormFileCollection();

            // Some of these code paths use StreamReader which does not support cancellation tokens.
            using (cancellationToken.Register(_request.HttpContext.Abort))
            {
                var contentType = ContentType;
                // Check the content-type
                if (HasApplicationFormContentType(contentType))
                {
                    var encoding = FilterEncoding(contentType.Encoding);
                    formFields = await FormReader.ReadFormAsync(_request.Body, encoding, cancellationToken);
                }
                else if (HasMultipartFormContentType(contentType))
                {
                    var formAccumulator = new KeyValueAccumulator<string, string>(StringComparer.OrdinalIgnoreCase);

                    var boundary = GetBoundary(contentType);
                    var multipartReader = new MultipartReader(boundary, _request.Body);
                    var section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    while (section != null)
                    {
                        var headers = new HeaderDictionary(section.Headers);
                        ContentDispositionHeaderValue contentDisposition;
                        ContentDispositionHeaderValue.TryParse(headers.Get(HeaderNames.ContentDisposition), out contentDisposition);
                        if (HasFileContentDisposition(contentDisposition))
                        {
                            // Find the end
                            await section.Body.DrainAsync(cancellationToken);

                            var file = new FormFile(_request.Body, section.BaseStreamOffset.Value, section.Body.Length)
                            {
                                Headers = headers,
                            };
                            files.Add(file);
                        }
                        else if (HasFormDataContentDisposition(contentDisposition))
                        {
                            // Content-Disposition: form-data; name="key"
                            //
                            // value

                            var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                            MediaTypeHeaderValue mediaType;
                            MediaTypeHeaderValue.TryParse(headers.Get(HeaderNames.ContentType), out mediaType);
                            var encoding = FilterEncoding(mediaType?.Encoding);
                            using (var reader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
                            {
                                var value = await reader.ReadToEndAsync();
                                formAccumulator.Append(key, value);
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.Assert(false, "Unrecognized content-disposition for this section: " + headers.Get(HeaderNames.ContentDisposition));
                        }

                        section = await multipartReader.ReadNextSectionAsync(cancellationToken);
                    }

                    formFields = formAccumulator.GetResults();
                }
            }

            Form = new FormCollection(formFields, files);
            return Form;
        }
        public void GetListT_KnownTypeWithValidValue_Success()
        {
            var headers = new HeaderDictionary();
            headers[HeaderNames.Accept] = "text/plain; q=0.9, text/other, */*";

            var result = headers.GetList<MediaTypeHeaderValue>(HeaderNames.Accept);

            var expected = new[] {
                new MediaTypeHeaderValue("text/plain", 0.9),
                new MediaTypeHeaderValue("text/other"),
                new MediaTypeHeaderValue("*/*"),
            }.ToList();
            Assert.Equal(expected, result);
        }
        public void GetListT_UnknownTypeWithTryParseListAndValidValue_Success()
        {
            var headers = new HeaderDictionary();
            headers["custom"] = "valid";

            var results = headers.GetList<TestHeaderValue>("custom");
            Assert.NotNull(results);
            Assert.Equal(new[] { new TestHeaderValue() }.ToList(), results);
        }