public async Task ChangesTo_SerializerSettings_AffectSerialization() { // Arrange var person = new User() { FullName = "John", age = 35 }; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User)); var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented, }; var expectedOutput = JsonConvert.SerializeObject(person, settings); var jsonFormatter = new NewtonsoftJsonOutputFormatter(settings, ArrayPool <char> .Shared); // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert var body = outputFormatterContext.HttpContext.Response.Body; Assert.NotNull(body); body.Position = 0; var content = new StreamReader(body, Encoding.UTF8).ReadToEnd(); Assert.Equal(expectedOutput, content); }
public void CanWriteResult_ReturnsExpectedValueForMediaType( string mediaType, bool isServerDefined, string expectedResult) { // Arrange var formatter = new NewtonsoftJsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared); var body = new MemoryStream(); var actionContext = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), body); var outputFormatterContext = new OutputFormatterWriteContext( actionContext.HttpContext, new TestHttpResponseStreamWriterFactory().CreateWriter, typeof(string), new object()) { ContentType = new StringSegment(mediaType), ContentTypeIsServerDefined = isServerDefined, }; // Act var actualCanWriteValue = formatter.CanWriteResult(outputFormatterContext); // Assert var expectedContentType = expectedResult ?? mediaType; Assert.Equal(expectedResult != null, actualCanWriteValue); Assert.Equal(new StringSegment(expectedContentType), outputFormatterContext.ContentType); }
public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding( string content, string encodingAsString, bool isDefaultEncoding) { // Arrange var formatter = new NewtonsoftJsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared); var formattedContent = "\"" + content + "\""; var mediaType = MediaTypeHeaderValue.Parse(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(mediaType, body); var outputFormatterContext = new OutputFormatterWriteContext( actionContext.HttpContext, new TestHttpResponseStreamWriterFactory().CreateWriter, typeof(string), content) { ContentType = new StringSegment(mediaType.ToString()), }; // Act await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.GetEncoding(encodingAsString)); // Assert var actualData = body.ToArray(); Assert.Equal(expectedData, actualData); }
public async Task ErrorDuringSerialization_DoesNotCloseTheBrackets() { // Arrange var expectedOutput = "{\"name\":\"Robert\""; var outputFormatterContext = GetOutputFormatterContext( new ModelWithSerializationError(), typeof(ModelWithSerializationError)); var serializerSettings = JsonSerializerSettingsProvider.CreateSerializerSettings(); var jsonFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, ArrayPool <char> .Shared); // Act try { await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); } catch (JsonSerializationException serializerException) { var expectedException = Assert.IsType <NotImplementedException>(serializerException.InnerException); Assert.Equal("Property Age has not been implemented", expectedException.Message); } // Assert var body = outputFormatterContext.HttpContext.Response.Body; Assert.NotNull(body); body.Position = 0; var content = new StreamReader(body, Encoding.UTF8).ReadToEnd(); Assert.Equal(expectedOutput, content); }
public async Task WriteToStreamAsync_LargePayload_DoesNotPerformSynchronousWrites() { // Arrange var model = Enumerable.Range(0, 1000).Select(p => new User { FullName = new string('a', 5000) }); var stream = new Mock <Stream> { CallBase = true }; stream.Setup(v => v.WriteAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <CancellationToken>())) .Returns(Task.CompletedTask); stream.SetupGet(s => s.CanWrite).Returns(true); var formatter = new NewtonsoftJsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared, new MvcOptions()); var outputFormatterContext = GetOutputFormatterContext( model, typeof(string), "application/json; charset=utf-8", stream.Object); // Act await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert stream.Verify(v => v.WriteAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <CancellationToken>()), Times.AtLeastOnce()); stream.Verify(v => v.Write(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>()), Times.Never()); stream.Verify(v => v.Flush(), Times.Never()); }
public async Task MvcJsonOptionsAreUsedToSetBufferThreshold() { // Arrange var person = new User() { FullName = "John", age = 35 }; Stream writeStream = null; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User), writerFactory: (stream, encoding) => { writeStream = stream; return(StreamWriter.Null); }); var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented, }; var expectedOutput = JsonConvert.SerializeObject(person, settings); var jsonFormatter = new NewtonsoftJsonOutputFormatter(settings, ArrayPool <char> .Shared, new MvcOptions(), new MvcNewtonsoftJsonOptions() { OutputFormatterMemoryBufferThreshold = 2 }); // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert Assert.IsType <FileBufferingWriteStream>(writeStream); Assert.Equal(2, ((FileBufferingWriteStream)writeStream).MemoryThreshold); }
public async Task MvcJsonOptionsAreUsedToSetBufferThresholdFromServices() { // Arrange var person = new User() { FullName = "John", age = 35 }; Stream writeStream = null; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User), writerFactory: (stream, encoding) => { writeStream = stream; return(StreamWriter.Null); }); var services = new ServiceCollection() .AddOptions() .Configure <MvcNewtonsoftJsonOptions>(o => { o.OutputFormatterMemoryBufferThreshold = 1; }) .BuildServiceProvider(); outputFormatterContext.HttpContext.RequestServices = services; var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented, }; var expectedOutput = JsonConvert.SerializeObject(person, settings); #pragma warning disable CS0618 // Type or member is obsolete var jsonFormatter = new NewtonsoftJsonOutputFormatter(settings, ArrayPool <char> .Shared, new MvcOptions()); #pragma warning restore CS0618 // Type or member is obsolete // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert Assert.IsType <FileBufferingWriteStream>(writeStream); Assert.Equal(1, ((FileBufferingWriteStream)writeStream).MemoryThreshold); }
private static Encoding CreateOrGetSupportedEncoding( NewtonsoftJsonOutputFormatter formatter, string encodingAsString, bool isDefaultEncoding) { Encoding encoding = null; if (isDefaultEncoding) { encoding = formatter.SupportedEncodings .First((e) => e.WebName.Equals(encodingAsString, StringComparison.OrdinalIgnoreCase)); } else { encoding = Encoding.GetEncoding(encodingAsString); formatter.SupportedEncodings.Add(encoding); } return(encoding); }
public JsonHalOutputFormatter(JsonSerializerSettings serializerSettings #if NET6_0 , MvcOptions mvcOpt #endif , IEnumerable <string> halJsonMediaTypes = null) { if (halJsonMediaTypes == null) { halJsonMediaTypes = new string[] { HalJsonType } } ; this.serializerSettings = serializerSettings; this.jsonFormatter = new JsonOutputFormatter(serializerSettings, ArrayPool <Char> .Create() #if NET6_0 , mvcOpt, null #endif ); this.halJsonMediaTypes = halJsonMediaTypes; }
public async Task WriteToStreamAsync_RoundTripsJToken() { // Arrange var beforeMessage = "Hello World"; var formatter = new NewtonsoftJsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared, new MvcOptions()); var memStream = new MemoryStream(); var outputFormatterContext = GetOutputFormatterContext( beforeMessage, typeof(string), "application/json; charset=utf-8", memStream); // Act await formatter.WriteResponseBodyAsync(outputFormatterContext, Encoding.UTF8); // Assert memStream.Position = 0; var after = JToken.Load(new JsonTextReader(new StreamReader(memStream))); var afterMessage = after.ToObject <string>(); Assert.Equal(beforeMessage, afterMessage); }