I access data in a database through a Web-Api and send it back as Json string to an UWP-App.
MessageRepository.cs:
public List<Message> GetByRecipientId(int id)
{
var listOfMsg = new List<Message>();
using (var ctx = new ShowcaseContext())
{
var recipientWithId = ctx.Recipients.Where(rec => rec.UserId == id);
foreach (var recipient in recipientWithId.ToList())
{
var msgWithId = ctx.Messages.Where(msg => msg.Id == recipient.MessageId);
listOfMsg.Add(msgWithId.Single());
}
return listOfMsg;
}
}
MessageController.cs:
[Route("api/message/recipient/{id}")]
public IEnumerable<Message> GetByRecipientId(int id)
{
return messageRepository.GetByRecipientId(id);
}
The problem is that I'm getting an
"Newtonsoft.Json.JsonSerializationException" Error
when trying to return listOfMsg
to the UWP-App.
But if I look at the List<>
and it items in debug mode, or access a specific message in the List<>
before returning it, the error disappeares and I get the right data in the UWP-App.
It seems like the List<>
has a different format before accessing it specifically which can't be serialized.
Has anyone an idea why?
Edit
Message.cs:
public class Message
{
public int Id { get; set; }
public virtual Collection<Recipient> Recipients { get; set; }
public MessageTrigger Trigger { get; set; }
public string Body { get; set; }
public DateTime CreatedTs { get; set; }
}
The StackTrace is null, but the error message is
The "ObjectContent`1" type failed to serialize the response body for content type "application/json; charset=utf-8".