如何从WCF返回Json序列化数据

本文关键字:Json 序列化 数据 返回 WCF | 更新日期: 2023-09-27 18:22:20

我环顾四周,发现可以从WCF web服务返回序列化到Json中的对象。有人知道我该怎么做吗?

感谢

如何从WCF返回Json序列化数据

您将不得不像这个一样为服务添加属性

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    ObjectName YourMethodName();

是的,您可以将automaticFormatSelectionEnabled设置为web.config中webHttpEndpoint的真正standardEndpoint,如

<webHttpEndpoint>
  <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>

您需要向客户端添加json响应的http头

using (HttpClient client = new HttpClient("endpoint"))
{
     HttpRequestMessage request = new HttpRequestMessage("GET", "SomeMethod");                
     request.Headers.Accept.AddString("application/json");
    ...
}