【问题标题】:WebAPI v2 - JSON Serialization for OData expand causes $type to be incorrectWebAPI v2 - OData 扩展的 JSON 序列化导致 $type 不正确
【发布时间】:2014-08-16 17:50:47
【问题描述】:

我刚刚将一个 MVC4/WebApi v1 应用程序更新为 MVC5 + WebAPI2..

似乎在这次升级之后,Json.Net 序列化程序将不再为使用 OData $expand 方法的请求包含正确的 $type。请参阅下面的示例,了解我的意思...

正确:

请求:http://url.com/api/Studies/277/Sites

回复:

{
$id: "1"
$type: "LGCYDAPI.Domain.Model.StudySiteWithContacts, LGCYDAPI.Domain.Model"
Contacts: [
{
$id: "2"
$type: "LGCYDAPI.Domain.Model.ContactRelatedToSite, LGCYDAPI.Domain.Model"
ContactID: -38445
}],
SiteID: 38445
}

不正确

请求:http://url.com/api/Studies/277/Sites?$expand=联系人

回复:

{
$id: "1"
$type: "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"
Contacts: [
{
$id: "2"
$type: "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"
ContactID: -38445
}],
SiteID: 38445}

连同 MVC 和 WebAPI 程序集,我将 JSON.NET 从 5.0.6 更新到 6.0.3,我认为这是问题所在。但是,我恢复到 v5 并没有解决问题,所以我回到 v6。还更新了 OData nuget - 我当前的版本是 Microsoft.Data.OData=5.6.0 和 Microsoft.AspNet.WebApi.OData=5.1.2。

JSON 序列化程序设置:

pConfiguration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
        pConfiguration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
        pConfiguration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;

        pConfiguration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());

【问题讨论】:

    标签: json asp.net-web-api json.net odata


    【解决方案1】:

    响应负载中的 $type 用于要序列化的实际对象。

    对结果应用$expand,返回对象的结构从LGCYDAPI.Domain.Model.StudySiteWithContacts变为SelectExpandWrapper

    因此,您无法在应用 $expand 的情况下获得预期的站点类型。

    对于SelectExpandWrapper 结构,请检查:

    https://aspnetwebstack.codeplex.com/wikipage?title=%24select%20and%20%24expand%20support

    【讨论】:

    • 感谢您提供的信息!您对我可以采取哪些替代方法或技巧来使 $type 读取对象的实际类型有任何想法吗? Breeze 非常依赖这个...
    • 1.尝试编写消息处理程序来分析响应内容类型,然后将其保存到响应中。 2.尝试发送另一个几乎相同的请求,但没有选择和扩展查询选项以获取实际类型。 3. 不要在请求 uri 中使用选择和查询选项。
    猜你喜欢
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2014-02-22
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多