11

I could use "TypeNameHandling = TypeNameHandling.Auto" in previous version of MVC. In MVC6, I have following class

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

In my webapi, JSON result will be the following

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

But I want the following result:

[
    {$type: "Foo", Id: "1", Name: "peter", Address: "address1"},
    {$type: "Bar", Id: "2", Account: "mary", Password: "1234"}
]
2
  • Looks like there is a bug currently. Filed one here: github.com/aspnet/Mvc/issues/3782 Commented Dec 17, 2015 at 22:07
  • can you post your api code please Commented Jan 10, 2016 at 1:18

1 Answer 1

1

You can add new field: type at BaseClass and initialize it at constructor:

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

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

At Foo class instances it will be "Foo", at Bar - "Bar".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.