Search code examples
c#asp.net-web-apiasp.net-web-api2odata

C# WebAPI not serializing dynamic properties correctly


I am creating a new C# OData4 Web API with a class named Call that has dynamic properties, which OData 4 allows via "Open Types". I believe I've set everything up and configured it correctly but the serialized response does not include the dynamic properties.

Did I configure something wrong?

public partial class Call 
{
    public int Id { get; set; }
    public string Email { get; set; }
    public IDictionary<string, object> DynamicProperties { get; }
}

public class CallController : ODataController
{
    [EnableQuery]
    public IQueryable<Call> GetCall([FromODataUri] int key)
    {
        return _context.Call.GetAll();
    }
}

public static partial class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        AllowUriOperations(config);

        ODataModelBuilder builder = new ODataConventionModelBuilder();
        builder.ComplexType<Call>();
        var model = builder.GetEdmModel();

        config.MapODataServiceRoute(RoutePrefix.OData4, RoutePrefix.OData4, model);    
    }

    private static void AllowUriOperations(HttpConfiguration config)
    {
        config.Count();
        config.Filter();
        config.OrderBy();
        config.Expand();
        config.Select();
    }
}

Solution

  • If the value in a key pair is null the property is simply not serialized. I was expecting it to be serialized to

    "key" : null

    Here are some additional examples

    DynamicProperties.Add("somekey", 1);
    

    "somekey" : 1


    DynamicProperties.Add("somekey", "1");
    

    "somekey" : "1"


    DynamicProperties.Add("somekey", null);