C# 使用WCF ResponseFormat=WebMessageFormat.Json时忽略类的属性

C# 使用WCF ResponseFormat=WebMessageFormat.Json时忽略类的属性,c#,wcf,json,C#,Wcf,Json,我将WCF用于JSON服务,使用以下格式: [OperationContract] [ServiceKnownType(typeof(ComplexResult))] [WebInvoke( Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)] MyClass MyFunction(stri

我将WCF用于JSON服务,使用以下格式:

[OperationContract]
[ServiceKnownType(typeof(ComplexResult))]
[WebInvoke(
            Method = "GET",
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Json)]
MyClass MyFunction(string myParams);
这很有效,但也有局限性。我不能忽略正在序列化为JSON的类的属性。如果我使用JavaScriptSerializer类,那么我可以将[ScriptIgnore]属性放在我想要忽略的属性上,它们不会在JSON中序列化,但是这不适用于上面的方法


是否有方法排除使用ResponseFormat JSON方法序列化为JSON的类的属性?

WCF默认使用
DataContractJsonSerializer
来序列化对象。根据
MyClass
的定义方式,您可以使用不同的属性来防止成员被序列化:

  • 如果MyClass没有任何属性(即,它是“POCO”类型),则可以在不希望序列化的成员中使用
    [IgnoreDataMember]
    属性
  • 如果MyClass用
    [Serializable]
    修饰,则可以在这些成员中使用
    [NotSerialized]
    属性
  • 如果MyClass是用
    [DataContract]
    修饰的,那么您只需不向不希望序列化的成员添加
    [DataMember]