AnisNoorAli
AnisNoorAli

Reputation: 81

Error when return custom class array from WEB API call

When I am returning array of Person class from WebAPI, I am getting following error when I call that WebAPI., Please help me how would I resolve the problem. WebAPI CODE

public class PersonController : ApiController
{
    public Person[] Get()
    {
        Person[] p = new Person[3]
        { 
            new Person("ABC", "XYZ", 1),
            new  Person("A", "B", 1),
            new Person("D", "E", 1)
         };

         return p;
   }

Person Class:

public class Person
{
    public String FirstName;
    public String LastName;
    public int PersonID;

    public Person(string fName, string lName, int id)
    {
        this.FirstName = fName;
        this.LastName = lName;
        this.PersonID = id;
    }
} 

This is the error i am getting:

An error has occurred. The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'. System.InvalidOperationException An error has occurred. Type 'ConsoleApplication1.Person' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types. System.Runtime.Serialization.InvalidDataContractException at ...

Upvotes: 0

Views: 394

Answers (2)

Arin Ghazarian
Arin Ghazarian

Reputation: 5305

It's just because your Person class doesn't have a default constructor. To resolve this issue just add a default constructor to your class:

public class Person
{
    public String FirstName;
    public String LastName;
    public int PersonID;

    public Person() {}

    public Person(string fName, string lName, int id)
    {
        this.FirstName = fName;
        this.LastName = lName;
        this.PersonID = id;
    }
} 

Upvotes: 0

brandon-irl
brandon-irl

Reputation: 115

The error is telling you a lot.

Type 'ConsoleApplication1.Person' cannot be serialized

The problem is in how you structured your Person model. ASP.NET Web API can automatically serialize a model, and include it in the body of the message so that the client can deserialize the object and read the data.

To make your model serializable, you need to have public getters and setters for the properties you want to transmit. Here is an example to get you started:

public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public int PersonID { get; set; }

    public Person(string fName, string lName, int id)
    {
        this.FirstName = fName;
        this.LastName = lName;
        this.PersonID = id;
    }
}

Furthermore, this site has some great information on ways you can manipulate your models to accomplish different things.

Upvotes: 0

Related Questions