无法将具有键值对数组的 JavaScript 对象发布到 Web Api

Trouble posting a JavaScript object with an array of Key Value Pairs to Web Api

我有一个对象(下面的模型)我已经用 JavaScript 填充了客户端,我需要 post 它到我的服务器。在我期望收到的 class 服务器端定义了相应类型的对象。

当我尝试 post 对象时,除单个 属性 外,一切 post 都很好。此 属性 在服务器端定义为 List<KeyValuePair<Guid,Bar>>Bar 似乎不是问题,因为我可以 post 就好了。

客户端,我尝试以几种方式重新格式化 JavaScript 对象上相应的 属性(作为对象对的数组,作为对象的文字属性等) .), 但它到达服务器时始终是一个空列表。

我猜这是一个语法问题,但我无法确定正确的语法是什么,而且我在网上看到很多相互矛盾的示例。我希望有人可以根据经验谈谈应该如何 posted。

//C# Class MockUp
public class Foo
{
    public Guid FooId {get;set;}
    public string Description {get;set;}
    public bool Inactive {get;set;}
    public List<KeyValuePair<Guid,Bar>> FooBar {get;set;} //This comes over as null regardless of how I arrange the object client-side.
}

//TypeScript Class MockUp
class Foo {
    fooId: string;
    description: string;
    inactive: boolean;
    fooBar: Array<KeyValuePair>;
}
class KeyValuePair {
    key: string;
    value: Bar
}
class Bar {
    //...Implementation here mathces Bar on the server
}

如果你为 foobar 创建一个 dto 就会工作

public class FooDto
{
    public Guid FooId {get;set;}
    public string Description {get;set;}
    public bool Inactive {get;set;}
    public List<FooBarDto> FooBar {get;set;} 
}

public class FooBarDto
{
    public Guid Key {get;set;}
    public Bar Value {get;set;}
}

之所以KeyValuePair在这种情况下不起作用是因为KeyValuePair中的属性是只读的,看这里 at the msdn docs你可以看到Key和Value proerties 只有 getters