0

I am looking for a code example to illustrate how to create a Model class in .net core MVC using C#, where the class has dynamic properties. My API receives a http POST request and I am creating one property for each HTTP header in the HeadersModel class of my API.

I am using .net core 3.1

namespace HttpsHeaders.Models
{
    public class Headers : DynamicObject
    {
        //public int ID { get; set; }
        //public string HeaderOne { get; set; }
//Instead of these properties, I want to add the properties dynamically
Dictionary<string, object> dictionary
            = new Dictionary<string, object>();
     }
}

If there is a better solution that dynamic object, please let me know as I am learning .net core C#.

EDIT: How serialize dynamic object to JSON string?

I could find instructions on how to create a dynamic object here: https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.dynamicobject?view=netcore-3.1

However, I cannot serialize the Headers object to string json. These instructions does not work and I get an empty string after serialization.

C# json object for dynamic properties How to serialize a dynamic object to a JSON string in dotnet core?

dynamic dynObjectInstance = new Headers ();
dynObjectInstance.Foo = "Bar"; 
string resultJson = JsonConvert.SerializeObject(dynObjectInstance);
\\ this returns "{}"
\\ I was expecting to get “{\”Foo\”:\”Bar\”}”
Mali Tbt
  • 679
  • 1
  • 8
  • 12

1 Answers1

0

I found a better solution than defining a model and it is using the ExpandObject.

    // ExpandoObject supports IDictionary so we can extend it like this
    dynamic expando = new ExpandoObject();
    var expandoDict = expando as IDictionary<string, object>;
    if (expandoDict.ContainsKey(propertyName))
        expandoDict[propertyName] = propertyValue;
    else
        expandoDict.Add(propertyName, propertyValue);
Mali Tbt
  • 679
  • 1
  • 8
  • 12