jacobvoller.com
jacobvoller.com

Reputation: 516

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();
    }
}

Upvotes: 5

Views: 1374

Answers (4)

dan zetea
dan zetea

Reputation: 187

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

Upvotes: 1

michalh
michalh

Reputation: 2997

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.

Upvotes: 1

jacobvoller.com
jacobvoller.com

Reputation: 516

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);

Upvotes: 0

TomDoesCode
TomDoesCode

Reputation: 3681

Can you check in your metadata, on the type Call do you have OpenType="true"? If not, try making it an EntitySet changing this line:

builder.ComplexType<Call>();

to this

builder.EntitySet<Call>("Calls");

If you do have OpenType="true" in your metadata, check that you definitely have some entries in your DynamicProperties collection

Upvotes: 0

Related Questions