Skip to content

🐛 Template.Context causes InvalidOperationException during JSON serialization #5

@gravity-api

Description

@gravity-api

When returning Template objects from the API, the Context field (a Dictionary<string, object?>) sometimes triggers the following error during response serialization:

System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(...)
   at System.Text.Json.Serialization.Converters.DictionaryDefaultConverter`3.OnWriteResume(...)

Impact:

  • The API request fails with HTTP 500.
  • Occurs when Context is modified while System.Text.Json is enumerating it during serialization.

Steps to Reproduce:

  1. Return a Template object with a Context dictionary that may be mutated after the object is passed to the controller’s return Ok(...).
  2. Trigger a concurrent update to Context during serialization.
  3. Observe the InvalidOperationException in logs and the failed API response.

Expected Behavior:

  • The API should return a successful JSON response, even if Context is being updated internally.
  • The serializer should iterate over a stable snapshot of the dictionary.

Possible Root Cause:

Template.Context is a mutable dictionary reference that is being updated while ASP.NET Core’s System.Text.Json serializer is enumerating it. This causes the dictionary’s enumerator to throw an InvalidOperationException.

Additional Notes:

This is a concurrency safety issue and can be fixed without changing the public API by ensuring the returned object is detached from any live mutable state.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions