Asp.Net的Web API错误:“ObjectContent`1”类型没有序列化响应正文内容类型“application / xml进行;字符集= UTF-8“ [英] Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'

查看:1512
本文介绍了Asp.Net的Web API错误:“ObjectContent`1”类型没有序列化响应正文内容类型“application / xml进行;字符集= UTF-8“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的例子,我得到一个集合,通过Web API尝试它输出:

Simplest example of this, I get a collection and try to output it via Web API:

// GET api/items
public IEnumerable<Item> Get()
{
    return MyContext.Items.ToList();
}

和我得到的错误:

类型的对象
  System.Data.Objects.ObjectQuery 1 [Dcip.Ams.BO.EquipmentWarranty]'
  不能转换为类型
  System.Data.Entity.DbSet
1 [Dcip.Ams.BO.EquipmentWarranty]

Object of type 'System.Data.Objects.ObjectQuery1[Dcip.Ams.BO.EquipmentWarranty]' cannot be converted to type 'System.Data.Entity.DbSet1[Dcip.Ams.BO.EquipmentWarranty]'

这是一个pretty常见的错误做了新的代理,我知道我可以通过设置解决这个问题:

This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:

MyContext.Configuration.ProxyCreationEnabled = false;

但是,这违背了很多我所试图做的目的。有没有更好的办法?

But that defeats the purpose of a lot of what I am trying to do. Is there a better way?

推荐答案

我只会在你不需要或者是造成你麻烦的地方建议禁用代理创建。你不必禁用它在全球范围你可以通过禁用code ...

I would suggest Disable Proxy Creation only in the place where you don't need or is causing you trouble. You don't have to disable it globally you can just disable the current DB context via code...

    [HttpGet]
    [WithDbContextApi]
    public HttpResponseMessage Get(int take = 10, int skip = 0)
    {
        CurrentDbContext.Configuration.ProxyCreationEnabled = false;

        var lista = CurrentDbContext.PaymentTypes
            .OrderByDescending(x => x.Id)
            .Skip(skip)
            .Take(take)
            .ToList();

        var count = CurrentDbContext.PaymentTypes.Count();

        return Request.CreateResponse(HttpStatusCode.OK, new { PaymentTypes = lista, TotalCount = count });
    }

在这里,我只在禁用这种方法ProxyCreation,因为每一个请求出现创造了一个新的DbContext,所以我只停用此情况下,ProxyCreation。
希望它能帮助

Here I only disabled the ProxyCreation in this method, because for every request there is a new DBContext created and therefore I only disabled the ProxyCreation for this case . Hope it helps

这篇关于Asp.Net的Web API错误:“ObjectContent`1”类型没有序列化响应正文内容类型“application / xml进行;字符集= UTF-8“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆