WCF Rest服务JSON序列化失败及WebService反序列化错误求助
刚好碰到过不少WCF相关的坑,给你整理了针对这两个问题的具体解决办法:
问题1:WCF Rest服务默认返回XML,无法序列化JSON
这个问题本质是WCF Rest默认的响应格式配置不对,有两种常用的解决方式:
方式一:通过配置文件全局设置
在你的web.config(或者app.config)的<system.serviceModel>节点下,添加对应的端点行为和绑定配置,指定默认响应格式为JSON:<system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="JsonBehavior"> <webHttp defaultOutgoingResponseFormat="Json" /> </behavior> </endpointBehaviors> </behaviors> <services> <service name="YourNamespace.YourService"> <endpoint address="" binding="webHttpBinding" contract="YourNamespace.IYourService" behaviorConfiguration="JsonBehavior" /> </service> </services> </system.serviceModel>方式二:通过代码属性局部设置
如果只想让某个接口方法返回JSON,可以在对应的[WebGet]或[WebInvoke]属性里指定响应格式:[ServiceContract] public interface IYourService { [WebGet(ResponseFormat = WebMessageFormat.Json)] [OperationContract] YourDataModel GetData(); [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] [OperationContract] bool PostData(YourDataModel model); }
问题2:WCF WebService反序列化报错,提示“预期‘root’但找到‘UserEmail’”
这个错误是因为WCF的DataContractSerializer默认期望字符串类型的参数被包裹在<root>标签里,但你的请求里传的是<UserEmail>标签,导致序列化不匹配。可以试试这几种方案:
方案一:调整请求格式匹配默认规则
把请求里的字符串用<root>标签包裹,比如原本的请求是:return (<UserEmail>test@example.com</UserEmail> )修改为:
test@example.com 方案二:定义对应的数据契约类
如果不想修改请求格式,可以创建一个和请求结构匹配的数据契约类,让服务方法接收这个类作为参数:[DataContract(Namespace = "")] public class EmailRequest { [DataMember(Name = "UserEmail")] public string UserEmail { get; set; } } // 然后修改服务接口 [ServiceContract] public interface IYourService { [OperationContract] void ProcessEmail(EmailRequest request); }这样WCF就能正确识别
<UserEmail>元素并反序列化到对应的属性里。方案三:改用XmlSerializer处理
如果一定要直接接收string类型的参数,可以在服务方法上添加[XmlSerializerFormat]属性,切换到XmlSerializer(它对根元素名称的限制更宽松):[ServiceContract] public interface IYourService { [OperationContract] [XmlSerializerFormat] void ProcessEmail(string UserEmail); }
内容的提问来源于stack exchange,提问作者Wilmer
相关产品推荐
相关产品推荐

