1

I've developed a very simple WebApi in order to test some Knockout.js features. IMO it should work properly, but when I make a GET request to the Api via Fiddler, it doesn't return any JSON at all.

I'm using MVC4's JSON default serializer.

This is my model...

public class Page
{
    public string Name { get; set; }
    public List<Control> Controls { get; set; }        
}

public abstract class Control
{
    public string Name { get; set; }
    public abstract string SayHi();
}

public class Form : Control
{
    public override string SayHi()
    {
        return string.Format("Hi, I'm form {0}", Name);
    }
}

public class Datagrid : Control
{
    public override string SayHi()
    {
        return string.Format("Hi, I'm datagrid {0}", Name);
    }
}

...here is my Controller...

public class PageController : ApiController
{
    static readonly ISimplePageRepository _repository = new TestPageRepository();

    // GET /api/page
    public IEnumerable<Page> GetAllPages()
    {
        return _repository.GetAll();
    }
}

...and just in case, this is my repo...

public class TestPageRepository : ISimplePageRepository
{
    private List<Page> _pages = new List<Page>();

    public TestPageRepository()
    {
        Add(new Page {Name = "pagina1", Controls = new List<Control>() {new Datagrid() {Name = "laTablita"}}});
        Add(new Page {Name = "pagina2", Controls = new List<Control>() {new Form() {Name = "elFormito"}}});
    }

    public Page Add(Page item)
    {
        _pages.Add(item);
        return item;
    }

    public IEnumerable<Page> GetAll()
    {
        return _pages.AsQueryable();
    }
}

Thanks in advance!

7
  • Is your Page class decorated with a Serializable attribute? Commented Apr 12, 2012 at 15:36
  • Already tried, but didn't work... also tried with the other classes but it didn't do the trick Commented Apr 12, 2012 at 15:39
  • If I change Page's Controls type to be a List<Form>, it works. Could be some problem with the abstract class? Commented Apr 12, 2012 at 15:41
  • A list of an abstract type may present a problem as the objects within that collection cannot be instantiated as that type, but shouldn't have a problem being instantiated as a subtype. Perhaps try refactoring that Page class to use a generic IEnumerable rather than a List of abstract types. Commented Apr 12, 2012 at 15:46
  • Nope, it still returns: e [{"Controls":[ ebe Commented Apr 12, 2012 at 15:51

1 Answer 1

1

I changed the default serializer to JSON.NET and it worked. Apparently, the problem was with the default serializer and the abstract Control class.

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.