【问题标题】:WCF serialization gotcha - Different behaviour Azure Web Role VS IISWCF 序列化陷阱 - Azure Web Role VS IIS 的不同行为
【发布时间】:2013-07-26 04:20:14
【问题描述】:

我在 WCF Web 服务中遇到了一个有趣的情况,我在 IIS 中运行的本地部署的应用程序和在 Azure 上运行的部署的 Web 角色之间遇到了不同的行为。

我有一个这样定义的类

[DataContract]
public class DefaultClassView : BaseView
{
    [DataMember]
    public Guid ClassID { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public Guid SchoolID { get; set; }

    [DataMember]
    public string SchoolName { get; set; }

    [DataMember]
    public IEnumerable<Guid> YearLevelIDs { get; set; }

    [DataMember]
    public IEnumerable<string> YearLevelNameList { get; set; }

    [DataMember]
    public IEnumerable<Guid> SubjectIDs { get; set; }

    [DataMember]
    public IEnumerable<string> SubjectNameList { get; set; }
}

然后使用以下代码填充该类

public static DefaultClassView ConvertToView(this Class entity)
{
    return new DefaultClassView()
    {
        ClassID = entity.ClassID,
        Name = entity.Name,
        YearLevelIDs = entity.Students.Select(o => o.YearLevelID).Distinct(),
        YearLevelNameList = entity.Students.Select(o => o.YearLevel.Name).Distinct(),
        SchoolID = entity.SchoolID,
        SchoolName = entity.School.Name,
        SubjectIDs = entity.Subjects.Select(o => o.SubjectID),
        SubjectNameList = entity.Subjects.Select(o => o.Name)
    };
}

在我将它部署在 Azure 上之前,此代码一直运行良好(在我的本地 IIS 实例中部署时),此时在激活服务时我开始收到以下错误。

Type System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Model.Subject,System.Guid]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. 

删除 LINQ 查询后,我能够成功解决此问题,但我想了解的是为什么两个平台之间的这种行为如此不同,如果这种行为是设计使然,我也想知道与在 Azure 上部署 WCF 服务相关的任何其他类似“陷阱”吗?

【问题讨论】:

    标签: c# .net wcf azure azure-web-roles


    【解决方案1】:

    在每次 LINQ 查询之后,调用 ToList()、First() 或 FirstOrDefault(),这样您就不会序列化 LINQ 类型,而是序列化预期的类型。

    【讨论】:

    • 对不起,我想我不清楚,我明白这一点,事实上这正是我解决问题的方式。我不明白为什么两个平台之间的这种行为不同。
    • 这是由于本地访问服务而不是远程服务器。
    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    相关资源
    最近更新 更多