![](/img/trans.png)
[英]"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json
[英]Always have error “The ObjectContent 1 type failed to serialize the response body…”
我使用Web api從數據庫中檢索數據。 我只有一個表“tblMessage”,並希望從該表中獲取數據。
我設置了所有內容但是當我運行網站時。 錯誤總是說
'ObjectContent`1'類型無法序列化內容類型'application / xml的響應主體
我在stackoverflow上讀了一些帖子,說明錯誤可以通過告訴瀏覽器以json格式輸出數據來修復。 之后,錯誤就變成了
'ObjectContent`1'類型無法序列化內容類型'application / json的響應主體
我已嘗試過以下帖子中的所有解決方案,但他們沒有解決問題(瀏覽器報告相同的錯誤)
Web API錯誤:'ObjectContent`1'類型無法序列化內容類型的響應正文
Web API錯誤:'ObjectContent`1'類型無法序列化內容類型的響應正文
這個錯誤究竟是什么?
public interface IMessage
{
IQueryable<Message> GetAll();
}
public class Message
{
[Key]
public int i_StmID { get; set; }
public string vch_MsgString { get; set; }
}
public class EFDBContext : DbContext
{
public DbSet<Message> Message { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Message>().ToTable("tblMessage");
}
}
public class MessageRepository : IMessage
{
private EFDBContext context = new EFDBContext();
public IQueryable<Message> GetAll()
{
return context.tblMessage;
}
}
public class MessageController : ApiController
{
public IMessage repo = new MessageRepository();
public IEnumerable<Message> GetAllMsg()
{
return repo.GetAll();
}
}
將IEnumerable<Message
>更改為List<Message>
public IEnumerable<Message> GetAllMsg()
{
return repo.GetAll();
}
至
public List<Message> GetAllMsg()
{
return repo.GetAll();
}
更新:但要注意獲取OutOfMemoryException
因為此方法將所有Message
對象存儲在本地內存中,因此您必須實現某種類型的分頁。
對於這些類型的數據查詢,您肯定應該為結果創建分頁。 在Web API中有2個分頁選項。
您可以使用OData從操作方法返回IQueryable對象的第一個選項。 這樣,您的操作支持分頁。
第二個選項是創建一個支持分頁的控制器。 我在下面舉了一個例子。
[HttpGet]
public List<Book> Books(int page = 0 , int size = 100){
using(var context = new BooksDataContext()){
List<Book> books = context.Books.OrderBy(t=> t.CreateDate).Skip(page * size).Take(size).ToList();
return books;
}
}
上面的代碼支持分頁,您可以設置將從客戶端返回的集合計數。
我與Chrome有同樣的問題,而不是IE。 為了解決這個問題,我在Global.asax.cs,Application_Start()方法中使用了以下幾行:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
我遇到了同樣的問題,這是我找到的解決方案
更新實體數據模型后,您必須在模型中將ProxyCreationEnabled
設置為false
Configuration.ProxyCreationEnabled = false;
我的例子:
public partial class EventsEntities : DbContext
{
public EventsEntities()
: base("name=EventsEntities")
{
Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.