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:
- Return a
Template object with a Context dictionary that may be mutated after the object is passed to the controller’s return Ok(...).
- Trigger a concurrent update to
Context during serialization.
- 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.
When returning
Templateobjects from the API, theContextfield (aDictionary<string, object?>) sometimes triggers the following error during response serialization:Impact:
Contextis modified whileSystem.Text.Jsonis enumerating it during serialization.Steps to Reproduce:
Templateobject with aContextdictionary that may be mutated after the object is passed to the controller’sreturn Ok(...).Contextduring serialization.InvalidOperationExceptionin logs and the failed API response.Expected Behavior:
Contextis being updated internally.Possible Root Cause:
Template.Contextis a mutable dictionary reference that is being updated while ASP.NET Core’sSystem.Text.Jsonserializer is enumerating it. This causes the dictionary’s enumerator to throw anInvalidOperationException.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.