WCF和城堡图书馆(Glass Mapper)

时间:2012-07-30 15:31:19

标签: wcf sitecore sitecore6 glass-mapper

你好我在Sitecore 6下有webHttpEndpointBehavior的WCF服务,我使用Glass Mapper读取项目,Glass mapper依赖于Castle库。

它运作良好,但我有一些合同的方法,如:

        [OperationContract]
        [WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        List<Shade> GetAllShades(int columns, int rows);

我尝试以JSON格式返回我的班级列表, 在使用SvcTraceViewer.exe调试我的服务时我发现了下一个错误:

  

尝试序列化参数时出错   :GetFamilyShadesResult。 InnerException消息是'Type   带有数据合约名称的'Castle.Proxies.ShadeProxy'   'ShadeProxy:http://schemas.datacontract.org/2004/07/Castle.Proxies'是   没想到。考虑使用DataContractResolver或添加任何类型   静态地知道已知类型的列表 - 例如,by   使用KnownTypeAttribute属性或将它们添加到列表中   传递给DataContractSerializer的已知类型。'。请参阅   InnerException以获取更多详细信息。

如何解决此问题? Castle.Proxies.ShadeProxy是Castle下的动态类,我无法使用KnownTypeAttribute

实际上如果我是JSON.net库并将结果返回为字符串,一切正常。

1 个答案:

答案 0 :(得分:4)

我假设您有一个类链接到通过Glass加载的其他类,例如

[SitecoreClass]
public class Shade{

    [SitecoreField]
    public virtual IEnumerable<AnotherClass> SomeField{get;set;}

    [SitecoreChildren]
    public virtual IEnumerable<AnotherClass> Children{get;set;}      
}
[SitecoreClass]
public class AnotherClass{}

允许延迟加载类Glass使用Castle生成的代理,因此在运行时将类加载到SomeField属性中时,实际上会获得AnotherClass类的子类。

要解决此问题,您必须明确告诉类将其他类作为具体类型加载,更新SitecoreField属性应解决此问题:

[SitecoreClass]
public class Shade{

    [SitecoreField(Setting=SitecoreFieldSettings.DontLazyLoad)]
    public virtual IEnumerable<AnotherClass> SomeField{get;set;}

    [SitecoreChildren(IsLazy=false)]
    public virtual IEnumerable<AnotherClass> Children{get;set;}
}
[SitecoreClass]
public class AnotherClass{}