C#WebAPI没有正确地序列化动态属性

问题描述 投票:5回答:4

我正在创建一个新的C#OData4 Web API,其中包含一个名为Call的类,它具有动态属性,OData 4允许通过“Open Types”。我相信我已经设置了所有内容并正确配置它,但序列化响应不包括动态属性。

我配置错了吗?

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();
    }
}
c# asp.net-web-api asp.net-web-api2 odata
4个回答
1
投票

您可以通过添加以下行来启用OData开放类型中的空值动态属性的序列化(在我的代码中,在方法Register(HttpConfiguration config)中的WebApiConfig.cs中)

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

然后我的null动态属性开始序列化。


0
投票

你可以检查你的元数据,在类型Call你有OpenType="true"?如果没有,尝试将它变成EntitySet改变这一行:

builder.ComplexType<Call>();

对此

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

如果您的元数据中确实有OpenType="true",请检查您的DynamicProperties集合中是否有一些条目


0
投票

如果密钥对中的值是null,则该属性不会被序列化。我期待它被序列化

“key”:null

以下是一些其他示例

DynamicProperties.Add("somekey", 1);

“somekey”:1


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

“somekey”:“1”


DynamicProperties.Add("somekey", null);


0
投票

或者可以使用configuration.SetSerializeNullDynamicProperty(true);,它更清洁,不言自明。

© www.soinside.com 2019 - 2024. All rights reserved.