CodexBloom - Programming Q&A Platform

C# - implementing Adding Dynamic Properties to Object using ExpandoObject in ASP.NET Core API

👀 Views: 36 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
c# asp.net-core json expandoobject C#

I'm not sure how to approach I'm updating my dependencies and I'm trying to create an API endpoint in my ASP.NET Core application where I can return a dynamic object with properties that are not known until runtime. I'm using `ExpandoObject` for this purpose. However, I seem to be working with issues when I try to serialize the `ExpandoObject` to JSON. The dynamic properties aren't being included in the response. Here's a simplified version of my code: ```csharp [ApiController] [Route("api/[controller]")] public class DynamicController : ControllerBase { [HttpGet] public IActionResult GetDynamicResponse() { dynamic expandoObject = new ExpandoObject(); expandoObject.Property1 = "Value1"; expandoObject.Property2 = 42; // Intentionally adding a dynamic property ((IDictionary<string, object>)expandoObject)["DynamicProperty"] = "DynamicValue"; return Ok(expandoObject); } } ``` When I hit the endpoint, the JSON response only includes `Property1` and `Property2`, but `DynamicProperty` is missing. I've tried different approaches, including casting `expandoObject` to `IDictionary<string, object>` and ensuring that the properties are set before the return statement, but nothing seems to work. I'm using ASP.NET Core 6.0 and the default JSON serializer. Is there something I might be missing here? What could be causing this behavior, or how can I ensure that all dynamically added properties are included in the response? This is for a CLI tool running on Ubuntu 20.04. Is there a better approach? The stack includes C# and several other technologies. I'd be grateful for any help.