Asp.Net Web API错误:'ObjectContent`1'类型无法序列化内容类型'application / xml的响应主体;字符集= UTF-8'

问题描述 投票:34回答:6

最简单的例子,我得到一个集合并尝试通过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]'

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

MyContext.Configuration.ProxyCreationEnabled = false;

但这违背了我想要做的很多事情的目的。有没有更好的办法?

entity-framework entity-framework-4 asp.net-web-api
6个回答
24
投票

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

    [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 });
    }

这里我只禁用此方法中的代理创建,因为对于每个请求都创建了一个新的DBContext,因此我只禁用此情况下的代理创建。希望能帮助到你


25
投票

如果你有导航属性并且你不想让它们非虚拟,你应该使用JSON.NET并将App_Start中的配置更改为使用JSON而不是XML! 安装JSON.NET后从NuGet中,在Register方法的WebApiConfig.cs中插入此代码

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

12
投票

如果您有导航属性,则将它们设为非虚拟。映射仍然有效,但它会阻止创建无法序列化的动态代理实体。

没有延迟加载在Web Api中很好,因为您没有持久连接并且无论如何都运行了.ToList()。


7
投票

我只是根据需要禁用了代理类:

    // GET: ALL Employee
    public IEnumerable<DimEmployee> Get()
    {
        using (AdventureWorks_MBDEV_DW2008Entities entities = new AdventureWorks_MBDEV_DW2008Entities())
        {
            entities.Configuration.ProxyCreationEnabled = false;
            return entities.DimEmployees.ToList();
        }
    }

4
投票

这对我有所帮助: 在Global.asax.cs的Application_Start函数中添加以下代码

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
    .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
    .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

3
投票

在我的情况下,返回的对象在其中有一个属性,其类型没有无参数/默认构造函数。通过向该类型添加零参数构造函数,可以成功序列化对象。

© www.soinside.com 2019 - 2024. All rights reserved.