我有一个WCF应用程序(.NET Frameword 4.6.2),它有以下端点:
[OperationContract]
[WebGet(UriTemplate = "Products/{id}")]
public ProductDTO GetProduct(string id)
{
return Services.GetProduct(id);
}我的DTO有一些属性,比如Name、Price,还有一个自定义属性字典。
[DataContract]
[Serializable]
public class ProductDTO
{
[DataMember(Name = "Props", IsRequired = true, EmitDefaultValue = false)]
public IDictionary<string, string> Props {get;set;}
}我使用来自.net的默认Json序列化程序向客户端发送响应,并以这种方式序列化字典属性:
{
"Key":"propKey",
"Value":"propValue"
}我希望它没有关键字“键”和“值”。我知道我们可以使用DataContractJsonSerializerSettings来更改这个设置,即UseSimpleDictionaryFormat。我的问题是如何更改此操作或所有操作契约的默认框架行为的设置?我知道我可以使用Json.Net来解决这个使用问题,但在短期内,我想坚持使用DataContractJsonSerializer。是否有一种方法可以覆盖行为,以便设置此设置?
我试图重写以下行为,但它没有工作。
public class DataContractJsonSerializerOperationBehavior : DataContractSerializerOperationBehavior
{
public DataContractJsonSerializerOperationBehavior(OperationDescription operation) : base(operation) {}
public DataContractJsonSerializerOperationBehavior(OperationDescription operation, DataContractFormatAttribute dataContractFormatAttribute) : base(operation, dataContractFormatAttribute) {}
public override XmlObjectSerializer CreateSerializer(System.Type type, string name, string ns, IList<System.Type> knownTypes)
{
/* Never called */
}
public override XmlObjectSerializer CreateSerializer(System.Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<System.Type> knownTypes)
{
/* Never called */
}
}我还为我的端点设置了行为:
foreach (OperationDescription operationDescription in serviceEndpoint.Contract.Operations)
{
DataContractSerializerOperationBehavior dataContractBehavior = operationDescription.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;
if (dataContractBehavior != null)
{
operationDescription.Behaviors.Remove(dataContractBehavior);
operationDescription.Behaviors.Add(new DataContractJsonSerializerOperationBehavior(operationDescription));
}
}发布于 2017-03-14 13:40:52
在花费了太多时间之后,我最终将默认序列化程序从DataContractSerializer更改为JSON.Net .我不认为用DataContractSerializer作为默认序列化程序来更改我所寻找的设置是不可能的。
发布于 2017-03-07 18:53:45
值得一看GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings也许能帮上忙
https://stackoverflow.com/questions/42655986
复制相似问题