1

I'm testing the new ApiController in asp.net mvc 4 beta but when I try to return an class that looks like the following only a few properties gets serialized?

public class PageModel : IPageModel {
    public string Id { get; set; }
    public virtual IPageMetadata Metadata { get; private set; }
    public PageModel() {
        Metadata = new PageMetadata();
    }
}

this is the code in my api controller

    // GET /api/pages/5
    public PageModel Get(string id) {
        return new PageModel { Id = "pages/1", Metadata = {Name = "Foo"} };
    }

and this is the result

{
Id: "pages/1",
Parent: null
}

Is it possible to get the complete object and not only a few things?

1 Answer 1

1

Readonly properties are not serialized. Make the setter of the Metadata property public if you want it to be serialized. I think that this behavior is normal for input parameters but not for output which is your case. IMHO it's a bug that could be workarounded by using a JSON serializer which supports this but maybe they will fix it before the final release and allow readonly properties to be serialized for output parameters.

Actually it's not a big pain, because you should be using view models anyway, so simply map your domain model to a view model and have your method return this view model which will contain only the properties that you need to actually expose to the client. This view model will contain properties with public getters and setters.

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

2 Comments

that did not solve the problem, or I mean I get another error when I changed it pastebin.com/gN23Axyr ... It seems like the default serializer doesn't handle serialization of IPageMetadata, if I change it to PageMetadata it works. Is there a better serializer included that can handle this and maybe to lowercase json instead of the BumbyCaps look?
You cannot serialize an interface, but you could maybe try and put a [KnownType(typeof(PageMetadata))] attribute on the PageModel class. This should fix the serialization of the Metadata property as long as the object reference type is PageMetadata.

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.