vtforester
vtforester

Reputation: 683

Use a base class as the return type in ApiController

Using the ASP.NET WebApi 4 RC, is it possible to have an ApiController's return type be a base class and actually return instances of derived classes? Trying to do this now results in an internal server error (500) when returning xml. Returning json using this method works correctly.

public class Base
{
    public int ID { get; set; }
}
public class Derived : Base
{
    public string Message { get; set; }
}
public class ValuesController : ApiController
{
    public IEnumerable<Base> Get()
    {
        return new Derived[] { 
            new Derived(){ Message="test"},
            new Derived(){ Message="another"}
        };
    }
}

It would seem that the XML serialization is what's throwing the error but all I can see is the generic 500 error.

Upvotes: 2

Views: 2564

Answers (2)

Rajat Mehta
Rajat Mehta

Reputation: 201

You might want to do it programmatically

    private static Type[] GetKnownType()
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        var knownTypes = new List<Type>();
        foreach (var assembly in assemblies)
        {
            knownTypes.AddRange(assembly.GetTypes().Where(x => x.BaseType == typeof (BaseResponse)).ToArray());
        }
        return knownTypes.ToArray();
    }

Do remember your child class MUST have a default constructor else you will get runtime serialization error.

Upvotes: 0

Maess
Maess

Reputation: 4146

Yes, you need to use the knowntype serialization hint:

[System.Runtime.Serialization.KnownType(typeof(Derived))]
public class Base
{
    public int ID { get; set; }
}

Upvotes: 1

Related Questions