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'

查看:121
本文介绍了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.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]' cannot be converted to type
'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'

这是一个很常见的错误与新的代理,我知道我可以修复它通过设置:

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?

推荐答案

我建议仅在不需要或正在引起的地方禁用代理创建你麻烦您不必全局禁用它,您只需通过代码禁用当前的数据库上下文...

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天全站免登陆