Esempio n. 1
0
        public async Task CustomSerializerSettingsObject_TakesEffect()
        {
            // Arrange
            var person = new User()
            {
                Name = "John", Age = 35
            };
            var expectedOutput = JsonConvert.SerializeObject(person, new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.Indented
            });

            var jsonFormatter = new JsonOutputFormatter();

            jsonFormatter.SerializerSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.Indented
            };

            var outputFormatterContext = GetOutputFormatterContext(person, typeof(User));

            // Act
            await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0;

            var streamReader = new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body, Encoding.UTF8);

            Assert.Equal(expectedOutput, streamReader.ReadToEnd());
        }
        public async Task CustomSerializerSettingsObject_TakesEffect()
        {
            // Arrange
            var person = new User() { Name = "John", Age = 35 };
            var expectedOutput = JsonConvert.SerializeObject(person, new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting = Formatting.Indented
            });

            var jsonFormatter = new JsonOutputFormatter();
            jsonFormatter.SerializerSettings = new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting = Formatting.Indented
            };

            var outputFormatterContext = GetOutputFormatterContext(person, typeof(User));

            // Act
            await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body);
            outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0;

            var streamReader = new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body, Encoding.UTF8);
            Assert.Equal(expectedOutput, streamReader.ReadToEnd());
        }
Esempio n. 3
0
        public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding(
            string content,
            string encodingAsString,
            bool isDefaultEncoding)
        {
            // Arrange
            var formatter        = new JsonOutputFormatter();
            var formattedContent = "\"" + content + "\"";
            var mediaType        = string.Format("application/json; charset={0}", encodingAsString);
            var encoding         = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding);
            var expectedData     = encoding.GetBytes(formattedContent);


            var body                   = new MemoryStream();
            var actionContext          = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), body);
            var outputFormatterContext = new OutputFormatterContext
            {
                Object           = content,
                DeclaredType     = typeof(string),
                HttpContext      = actionContext.HttpContext,
                SelectedEncoding = encoding
            };

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            var actualData = body.ToArray();

            Assert.Equal(expectedData, actualData);
        }
Esempio n. 4
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            string callback;

            if (IsJsonpRequest(context.HttpContext.Request, _callbackQueryParameter, out callback))
            {
                if (!CallbackValidator.IsValid(callback))
                {
                    throw new InvalidOperationException($"Callback '{callback}' is invalid!");
                }

                using (var writer = context.WriterFactory(context.HttpContext.Response.Body, selectedEncoding))
                {
                    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
                    // the typeof check is just to reduce client error noise
                    var str = "/**/ typeof " + callback + " === 'function' && " + callback + "(";
                    str += context.Object + ");";
                    writer.Write("/**/ typeof " + callback + " === 'function' && " + callback + "(");
                    writer.Flush();
                    _jsonMediaTypeFormatter.WriteObject(writer, context.Object);
                    writer.Write(");");
                    await writer.FlushAsync();
                }
            }
            else
            {
                await _jsonMediaTypeFormatter.WriteResponseBodyAsync(context, selectedEncoding);
            }
        }
Esempio n. 5
0
        public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding(
            string content,
            string encodingAsString,
            bool isDefaultEncoding)
        {
            // Arrange
            var formatter        = new JsonOutputFormatter();
            var formattedContent = "\"" + content + "\"";
            var mediaType        = string.Format("application/json; charset={0}", encodingAsString);
            var encoding         = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding);
            var preamble         = encoding.GetPreamble();
            var data             = encoding.GetBytes(formattedContent);
            var expectedData     = new byte[preamble.Length + data.Length];

            Buffer.BlockCopy(preamble, 0, expectedData, 0, preamble.Length);
            Buffer.BlockCopy(data, 0, expectedData, preamble.Length, data.Length);

            var memStream = new MemoryStream();
            var outputFormatterContext = new OutputFormatterContext
            {
                Object           = content,
                DeclaredType     = typeof(string),
                ActionContext    = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), memStream),
                SelectedEncoding = encoding
            };

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            var actualData = memStream.ToArray();

            Assert.Equal(expectedData, actualData);
        }
Esempio n. 6
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var settings = FormatterUtils.GetSettings(context.HttpContext.RequestServices);

            var formatter = new JsonOutputFormatter(settings, ArrayPool <char> .Shared);

#if DEBUG
            var timer = new Stopwatch();
            timer.Start();
#endif
            await formatter.WriteResponseBodyAsync(context, selectedEncoding);

#if DEBUG
            timer.Stop();
            Console.WriteLine($"Write response: {timer.Elapsed.TotalMilliseconds}");
#endif
        }
Esempio n. 7
0
        public async Task WriteToStreamAsync_RoundTripsJToken()
        {
            // Arrange
            var beforeMessage          = "Hello World";
            var formatter              = new JsonOutputFormatter();
            var before                 = new JValue(beforeMessage);
            var memStream              = new MemoryStream();
            var outputFormatterContext = GetOutputFormatterContext(
                beforeMessage,
                typeof(string),
                "application/json; charset=utf-8",
                memStream);

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            memStream.Position = 0;
            var after        = JToken.Load(new JsonTextReader(new StreamReader(memStream)));
            var afterMessage = after.ToObject <string>();

            Assert.Equal(beforeMessage, afterMessage);
        }
 public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
 => _jsonOutputFormatter.WriteResponseBodyAsync(context, selectedEncoding);
        public async Task WriteToStreamAsync_RoundTripsJToken()
        {
            // Arrange
            var beforeMessage = "Hello World";
            var formatter = new JsonOutputFormatter();
            var before = new JValue(beforeMessage);
            var memStream = new MemoryStream();
            var outputFormatterContext = GetOutputFormatterContext(
                                                        beforeMessage,
                                                        typeof(string),
                                                        "application/json; charset=utf-8",
                                                        memStream);

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            memStream.Position = 0;
            var after = JToken.Load(new JsonTextReader(new StreamReader(memStream)));
            var afterMessage = after.ToObject<string>();

            Assert.Equal(beforeMessage, afterMessage);
        }
        public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding(
            string content,
            string encodingAsString,
            bool isDefaultEncoding)
        {
            // Arrange
            var formatter = new JsonOutputFormatter();
            var formattedContent = "\"" + content + "\"";
            var mediaType = string.Format("application/json; charset={0}", encodingAsString);
            var encoding = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding);
            var preamble = encoding.GetPreamble();
            var data = encoding.GetBytes(formattedContent);
            var expectedData = new byte[preamble.Length + data.Length];
            Buffer.BlockCopy(preamble, 0, expectedData, 0, preamble.Length);
            Buffer.BlockCopy(data, 0, expectedData, preamble.Length, data.Length);

            var memStream = new MemoryStream();
            var outputFormatterContext = new OutputFormatterContext
            {
                Object = content,
                DeclaredType = typeof(string),
                ActionContext = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), memStream),
                SelectedEncoding = encoding
            };

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            var actualData = memStream.ToArray();
            Assert.Equal(expectedData, actualData);
        }
Esempio n. 11
0
        public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding(
            string content,
            string encodingAsString,
            bool isDefaultEncoding)
        {
            // Arrange
            var formatter = new JsonOutputFormatter();
            var formattedContent = "\"" + content + "\"";
            var mediaType = string.Format("application/json; charset={0}", encodingAsString);
            var encoding = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding);
            var expectedData = encoding.GetBytes(formattedContent);


            var body = new MemoryStream();
            var actionContext = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), body);
            var outputFormatterContext = new OutputFormatterContext
            {
                Object = content,
                DeclaredType = typeof(string),
                HttpContext = actionContext.HttpContext,
                SelectedEncoding = encoding
            };

            // Act
            await formatter.WriteResponseBodyAsync(outputFormatterContext);

            // Assert
            var actualData = body.ToArray();
            Assert.Equal(expectedData, actualData);
        }
Esempio n. 12
0
 public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
 => _jsonOutputFormatter.WriteResponseBodyAsync(context, selectedEncoding);          // respond with this header info instead of default textoutputformatter