c# - 考虑使用 DataContractResolver 序列化错误

标签 c# serialization asp.net-web-api

我的桌面 wpf 应用程序与 mvc 4 web api 通信。我正在尝试读取所有数据库条目。这是一个简单的界面:

public interface IEventRepository
{
    IEnumerable<Event> GetAll();
}

这是存储库:

public class EventRepository : IEventRepository
{
    private List<Event> events = new List<Event>();
    public EventRepository()
    {
        HeronEntities context = new HeronEntities();
        events = context.Events.ToList();
    }

    public IEnumerable<Event> GetAll()
    {
        return events;
    }
 }

这是 Controller :

 public class EventController : ApiController
{
    static readonly IEventRepository repository = new EventRepository();

    public IEnumerable<Event> GetAllEvents()
    {
        return repository.GetAll();
    }
}

事件类如下所示:

public partial class Event
{
    public Event()
    {
        this.Comments = new HashSet<Comment>();
        this.Rates = new HashSet<Rate>();
        this.RawDates = new HashSet<RawDate>();
    }

    public int ID { get; set; }
    public string Title { get; set; }
    public string Summary { get; set; }
    public string SiteURL { get; set; }
    public string ContactEmail { get; set; }
    public string LogoURL { get; set; }
    public int EventType_ID { get; set; }
    public Nullable<int> Location_ID { get; set; }
    public Nullable<System.DateTime> BegginingDate { get; set; }
    public string nTrain { get; set; }
    public string Content { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual Conference Conference { get; set; }
    public virtual ICollection<Rate> Rates { get; set; }
    public virtual ICollection<RawDate> RawDates { get; set; }
    public virtual EventType EventType { get; set; }
    public virtual Location Location { get; set; }
}

当我尝试访问 Controller 时,出现上面提到的 failed to serialize the response body for content type 错误。 Event 类序列化存在一些问题。我对包含原始类型的类使用了完全相同的代码,并且效果很好。克服这种序列化问题的最佳方法是什么?

最佳答案

我已禁用延迟加载和代理类生成。这解决了问题。

public EventRepository()
    {
        HeronEntities context = new HeronEntities();
        context.Configuration.LazyLoadingEnabled = false;
        context.Configuration.ProxyCreationEnabled = false;
        events = context.Events.ToList();
    }

关于c# - 考虑使用 DataContractResolver 序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15707437/

相关文章:

c# - .NET 中的 Xml 序列化

c# - 我可以将基于接口(interface)的对象传递给 MVC 4 WebApi POST 吗?

c# - WPF slider 仅可拖动

c# - PagedList 使用 LINQ Skip and Take,但使用结果计数显示分页

c# - 使用反射将 JSON 字符串反序列化为类

java - 使用 GSON 反序列化为 ImmutableMap

C# .Net Core 依赖注入(inject),向构造函数注入(inject)多个参数

C# 解压缩后删除 .ZIP 文件

c# - Web API ViewModel 模式中可能存在不良实践?

c# - Web Api 请求抛出 "Error while copying content to a stream."