我可以在以前版本的MVC中使用“TypeNameHandling = TypeNameHandling.Auto”。 在MVC6中,我有以下课程
public class BaseClass {
public string Id {get;set;}
}
public class Foo : BaseClass {
public string Name {get;set;}
public string Address {get;set;}
}
public class Bar : BaseClass {
public string Account {get;set;}
public string Password {get;set;}
}
在我的webapi中,JSON结果将是以下
[
{Id: "1", Name: "peter", Address: "address1"},
{Id: "2", Account: "mary", Password: "1234"}
]
但我想要以下结果:
[
{$type: "Foo", Id: "1", Name: "peter", Address: "address1"},
{$type: "Bar", Id: "2", Account: "mary", Password: "1234"}
]
答案 0 :(得分:1)
您可以在BaseClass中添加新字段:类型并在构造函数中初始化它:
public class BaseClass {
public string Id {get;set;}
public readonly string type;
public BaseClass()
{
type = this.GetType().Name;
}
}
在Foo类实例中,它将是" Foo",在Bar - " Bar"。