Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 231
Jacob C. Voller Avatar asked Oct 30 '22 14:10

Jacob C. Voller


2 Answers

You can enable serialization of null valued dynamic properties in OData open types by adding the following line (in my code in WebApiConfig.cs in method Register(HttpConfiguration config))

    config.Properties.AddOrUpdate("System.Web.OData.NullDynamicPropertyKey", val=>true, (oldVal,newVal)=>true);

Then my dynamic properties with nulls start to serialize.

like image 85
michalh Avatar answered Nov 12 '22 22:11

michalh


Or configuration.SetSerializeNullDynamicProperty(true); can be used, which is more cleaner and self-explanatory.

like image 45
dan zetea Avatar answered Nov 12 '22 21:11

dan zetea