【发布时间】:2026-01-20 06:05:02
【问题描述】:
我想用 WCF 编写一个 RESTful Web 服务,它能够以 JSON 和 XML 回复。我有一个 XML 模式,我使用xsd.exe 从中生成了我的类。只要我请求 XML,一切都可以正常工作,但如果我想要 JSON 作为响应,它就会失败。
System.ServiceModel.Dispatcher.MultiplexingDispatchMessageFormatter 抛出 System.Collections.Generic.KeyNotFoundException。问题是,到目前为止,我发现xsd.exe 不会生成DataContract 和DataMember 属性。有没有什么解决方案我不需要使用SvcUtil.exe,因为因此我需要更改我的架构..
那是它失败的代码,JsonDispatchMessageFormatter 的类型是MultiplexingDispatchMessageFormatter。 (反正这是默认类型)
var headers = requestProperty.Headers[HttpRequestHeader.Accept] ?? requestProperty.Headers[HttpRequestHeader.ContentType];
if (headers != null && headers.Contains("application/json"))
{
return this.JsonDispatchMessageFormatter.SerializeReply(messageVersion, parameters, result);
}
生成的代码:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="...")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="...", IsNullable=false)]
public partial class Incident {
private long incidentIdField;
/// <remarks/>
public long IncidentId {
get {
return this.incidentIdField;
}
set {
this.incidentIdField = value;
}
}
}
【问题讨论】:
-
在重新调整之前尝试添加
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json"; -
将
"application/json"添加到传出响应中允许我现在序列化为json,但我还有一个问题。 XML 和 JSON 都序列化支持字段而不是属性。我可以为我的服务合同使用属性XmlSerializerFormat来避免XML 的这种情况,但是我再次不能使用JSON,因为它不喜欢这个属性。它建议我使用DataContractFormatAttribute,这将再次导致序列化支持字段..
标签: c# json xml wcf serialization