1
1
// Copyright (c) .NET Foundation. All rights reserved.
2
2
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3
3
4
+ using System . IO ;
5
+ using System . Text ;
6
+ using System . Text . Json . Serialization ;
7
+ using System . Threading . Tasks ;
8
+ using Microsoft . Extensions . Primitives ;
9
+ using Microsoft . Net . Http . Headers ;
10
+ using Xunit ;
11
+
4
12
namespace Microsoft . AspNetCore . Mvc . Formatters
5
13
{
6
14
public class SystemTextJsonOutputFormatterTest : JsonOutputFormatterTestBase
@@ -9,5 +17,51 @@ protected override TextOutputFormatter GetOutputFormatter()
9
17
{
10
18
return SystemTextJsonOutputFormatter . CreateFormatter ( new JsonOptions ( ) ) ;
11
19
}
20
+
21
+ [ Fact ]
22
+ public async Task WriteResponseBodyAsync_AllowsConfiguringPreserveReferenceHandling ( )
23
+ {
24
+ // Arrange
25
+ var formatter = GetOutputFormatter ( ) ;
26
+ ( ( SystemTextJsonOutputFormatter ) formatter ) . SerializerOptions . ReferenceHandling = ReferenceHandling . Preserve ;
27
+ var expectedContent = "{\" $id\" :\" 1\" ,\" name\" :\" Person\" ,\" child\" :{\" $id\" :\" 2\" ,\" name\" :\" Child\" ,\" child\" :null,\" parent\" :{\" $ref\" :\" 1\" }},\" parent\" :null}" ;
28
+ var person = new Person
29
+ {
30
+ Name = "Person" ,
31
+ Child = new Person { Name = "Child" , } ,
32
+ } ;
33
+ person . Child . Parent = person ;
34
+
35
+ var mediaType = MediaTypeHeaderValue . Parse ( "application/json; charset=utf-8" ) ;
36
+ var encoding = CreateOrGetSupportedEncoding ( formatter , "utf-8" , isDefaultEncoding : true ) ;
37
+
38
+ var body = new MemoryStream ( ) ;
39
+ var actionContext = GetActionContext ( mediaType , body ) ;
40
+
41
+ var outputFormatterContext = new OutputFormatterWriteContext (
42
+ actionContext . HttpContext ,
43
+ new TestHttpResponseStreamWriterFactory ( ) . CreateWriter ,
44
+ typeof ( Person ) ,
45
+ person )
46
+ {
47
+ ContentType = new StringSegment ( mediaType . ToString ( ) ) ,
48
+ } ;
49
+
50
+ // Act
51
+ await formatter . WriteResponseBodyAsync ( outputFormatterContext , Encoding . GetEncoding ( "utf-8" ) ) ;
52
+
53
+ // Assert
54
+ var actualContent = encoding . GetString ( body . ToArray ( ) ) ;
55
+ Assert . Equal ( expectedContent , actualContent ) ;
56
+ }
57
+
58
+ private class Person
59
+ {
60
+ public string Name { get ; set ; }
61
+
62
+ public Person Child { get ; set ; }
63
+
64
+ public Person Parent { get ; set ; }
65
+ }
12
66
}
13
67
}
0 commit comments