Skip to content
This repository was archived by the owner on Dec 14, 2018. It is now read-only.
This repository was archived by the owner on Dec 14, 2018. It is now read-only.

JsonOutputFormatter adds all closing brackets when exceptions are thrown #5413

@Tratcher

Description

@Tratcher

RE: aspnet/IISIntegration#285
When there are exceptions thrown part way through object serialization the output incorrectly closes out all of the }, making the serialized result appear complete/valid rather than truncated.

Repro (reduced from JsonOutputFormatter):

    public class Program
    {
        public static void Main(string[] args)
        {
            var stream = new MemoryStream();
            try
            {
                using (var textWriter = new StreamWriter(stream, Encoding.UTF8, 1024, leaveOpen: true))
                {
                    // var jsonWriter = new JsonTextWriter(textWriter) { CloseOutput = false };
                    using (var jsonWriter = new JsonTextWriter(textWriter) { CloseOutput = false })
                    {
                        var serializer = JsonSerializer.Create();
                        serializer.Serialize(jsonWriter, new Foo());
                    }
                    // jsonWriter.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            stream.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(stream);
            Console.WriteLine(reader.ReadToEnd());
        }
    }

    public class Foo
    {
        public string A { get; } = "A";
        public string B
        {
            get
            {
                // return "B";
                throw new NotImplementedException("get_B");
            }
        }
    }

Expected output:
{"A":"A"

Actual output:
{"A":"A"}

Recommended fix:
Remove the using statement around the JsonTextWriter and only call Close on it if the serialization completes successfully.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions