2015-12-17 10 views
11

Mogę użyć "TypeNameHandling = TypeNameHandling.Auto" w poprzedniej wersji MVC. W MVC6, mam następujące klasyJak określić typ polimorficzny w ASP.NET mvc 6

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

W moim WebAPI, wynik JSON będzie następujący

[ 
    {Id: "1", Name: "peter", Address: "address1"}, 
    {Id: "2", Account: "mary", Password: "1234"} 
] 

Ale chcę następujący wynik:

[ 
    {$type: "Foo", Id: "1", Name: "peter", Address: "address1"}, 
    {$type: "Bar", Id: "2", Account: "mary", Password: "1234"} 
] 
+0

Wygląda na to, że obecnie jest błąd. Złożyć tutaj: https://github.com/aspnet/Mvc/issues/3782 –

+0

czy możesz wysłać swój kod api proszę –

Odpowiedz

1

można dodawać nowe pole: wpisz w BaseClass i zainicjuj go w konstruktorze:

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

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

W instancjach klasy Foo będzie to "Foo", na pasku - "Bar".