Unexpected type when serializing web API

Asked

Viewed 907 times

3

I am trying to use the Web Api and getting this error while trying to serialize an array.

The 'HT.Data.Client' type with data contract name 'Client:http://schemas.datacontract.org/2004/07/HT.Data' is not expected. Consider using a Datacontractresolver if you are using a or Datacontractserializer add any statically unknown types to the list of known types - for example, using the Knowntypeattribute attribute or addingthe list of known types transmitted to the serializer.

My class that sits in a different web API project:

namespace HT.Data
{
    [DataContract]
    public partial class Client
    {
        [Key]
        [DataMember(Order = 1, IsRequired = true)]
        [Required(ErrorMessage = "Campo obrigatorio")] 
        [MaxLength(128, ErrorMessage = "Tamanho maximo do campo: 128 caracteres. ")]
        public string Id { get; set; } // Id (Primary key)


        [DataMember(Order = 2, IsRequired = true)]
        [Required(ErrorMessage = "Campo obrigatorio")] 
        public string Secret { get; set; } // Secret


        [DataMember(Order = 3, IsRequired = true)]
        [Required(ErrorMessage = "Campo obrigatorio")] 
        [MaxLength(100, ErrorMessage = "Tamanho maximo do campo: 100 caracteres. ")]
        public string Name { get; set; } // Name


        [DataMember(Order = 4, IsRequired = true)]
        [Required(ErrorMessage = "Campo obrigatorio")] 
        public int ApplicationType { get; set; } // ApplicationType


        [DataMember(Order = 5, IsRequired = true)]
        [Required(ErrorMessage = "Campo obrigatorio")] 
        public bool Active { get; set; } // Active


        [DataMember(Order = 6, IsRequired = true)]
        [Required(ErrorMessage = "Campo obrigatorio")] 
        public int RefreshTokenLifeTime { get; set; } // RefreshTokenLifeTime


        [DataMember(Order = 7, IsRequired = false)]
        [MaxLength(100, ErrorMessage = "Tamanho maximo do campo: 100 caracteres. ")]
        public string AllowedOrigin { get; set; } // AllowedOrigin


        public Client()
        {
            InitializePartial();
        }

        partial void InitializePartial();
    }

My controller:

namespace App.ResourceServer.Controllers
{
    //[Authorize]
    [RoutePrefix("api/sample")]
    public class SampleController : ApiController
    {    
        private UnitOfWork db = new UnitOfWork();

        [Route("")]
        public IEnumerable<object> Get()
        {    
            Client[] Result = db.ClientRepository.GetAllClients().ToArray(); 
            return Result;
        }
    }
}

And the startup of my API:

namespace AngularJSAuthentication.ResourceServer.App_Start
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonFormatter.SerializerSettings.ContractResolver.ResolveContract(typeof(Client));

        }
    }
}

How to configure the class to be known/expected?

  • Can you serialize only one element? For example instead of your method Get return Result he return Result[0] everything goes right? Your class is partial (partial), show your class in full.

  • It’s not just taking the attribute [DataContract] class Cliente?

  • I have the same curiosity as @jbueno. Pq vc added the notation DataContract?

2 answers

1

I solved this error by adding in Global.asax.Cs file, Application_start method

        //configura retorno json
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        GlobalConfiguration.Configuration.Formatters
            .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

0

How would I solve:

  1. Create a test project;
  2. Install your class with dummy values;
  3. Try to serialize using the same serializer as your main application EX: If you are Newtonsoft, just use Jsonconvert.Serializeobject(obj);

  4. Probably you will have the same problem, just inspect the error and identify which property it is complaining about.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.