2

I'm using ASP.NET Web API and I'm trying to return an instance of a class that looks like this:

public class Whatever
{
  public int MyInt {get; set;}
  public IFoo MyFoo {get; set;}
}

When this instance gets serialized to JSON, the IFoo member (which could be an instance of any of a number of classes implementing IFoo) gets serialized oddly. The property name is written, but its value is a huge chunk of HTML containing an error message like this:

You must write an attribute 'type'='object' after writing the attribute with local name '__type'.

Is this the framework telling me that it doesn't know how to serialize an instance cast as an interface? Or something else?

2
  • 1
    A downvote with no explanation serves no purpose. Commented May 2, 2012 at 15:36
  • My experiments suggest that the problem is that the member is expressed as an interface. When expressed as concrete type, the error disappears. But there are scenarios where I need to be able to assign multiple types to the same member of the class. What do I do then? Commented May 2, 2012 at 15:39

1 Answer 1

3

It appears that this error occurs whenever the framework tries to serialize a member whose type is an interface. Apart from changing the member so that its type is concrete, I can find no other way around this problem.

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

2 Comments

Yes, you cannot serialize an interface. You have to provide KnownTypes and all that. avoid exposing interfaces in your Web API.
Thanks for your response. I've never come across the KnownTypes thing before. As you say, it's probably not great design to have an interface member in a view model class anyway.

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.