Подтвердить что ты не робот

Как указать полиморфный тип в ASP.NET mvc 6

Я мог бы использовать "TypeNameHandling = TypeNameHandling.Auto" в предыдущей версии MVC. В 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"}
]
4b9b3361

Ответ 1

Вы можете добавить новое поле: тип в BaseClass и инициализировать его в конструкторе:

public class BaseClass {
    public string Id {get;set;}

    public readonly string type;
    public BaseClass()
    {
        type = this.GetType().Name;
    }
}

В экземплярах класса Foo это будет "Foo", в Bar - "Bar".