4
4
using System . Collections . Generic ;
5
5
using System . Linq ;
6
6
using System . Text . Json ;
7
+ using System . Text . Json . Serialization ;
7
8
using System . Threading ;
8
9
using System . Threading . Tasks ;
9
10
using Logging ;
@@ -27,7 +28,7 @@ public async Task Write(List<StartupDiagnosticEntries.StartupDiagnosticEntry> en
27
28
28
29
try
29
30
{
30
- data = JsonSerializer . Serialize ( dictionary ) ;
31
+ data = JsonSerializer . Serialize ( dictionary , diagnosticsOptions ) ;
31
32
}
32
33
catch ( Exception exception )
33
34
{
@@ -80,6 +81,26 @@ await diagnosticsWriter(data, cancellationToken)
80
81
readonly Func < string , CancellationToken , Task > diagnosticsWriter ;
81
82
readonly bool isCustomWriter ;
82
83
84
+ static readonly JsonSerializerOptions diagnosticsOptions = new ( )
85
+ {
86
+ Converters = { new TypeConverter ( ) }
87
+ } ;
88
+
89
+ /// <summary>
90
+ /// By default System.Text.Json would throw with "Serialization and deserialization of 'System.Type' instances are not supported" which normally
91
+ /// would make sense because it can be considered unsafe to serialize and deserialize types. We add a custom converter here to make
92
+ /// sure when diagnostics entries accidentally use types it will just print the full name as a string. We never intent to read these things
93
+ /// back so this is a safe approach.
94
+ /// </summary>
95
+ sealed class TypeConverter : JsonConverter < Type >
96
+ {
97
+ // we never need to deserialize
98
+ public override Type Read ( ref Utf8JsonReader reader , Type typeToConvert , JsonSerializerOptions options ) => throw new NotImplementedException ( ) ;
99
+
100
+ public override void Write ( Utf8JsonWriter writer , Type value , JsonSerializerOptions options ) => writer . WriteStringValue ( value . FullName ) ;
101
+ }
102
+
103
+
83
104
static readonly ILog logger = LogManager . GetLogger < HostStartupDiagnosticsWriter > ( ) ;
84
105
}
85
106
}
0 commit comments