有类似的问题,但它们涉及返回自动解析为JSON的对象。
我有一个包含JSON格式数据的字符串,我只想从WCF Web服务返回,以便我可以在ajax中读取它。
它只是返回字符串不起作用(我从ajax得到一个解析器错误)。我想知道我是否应该从Web服务返回我的JSON字符串?
我的ajax很好,因为我已经使用其他提供Web服务的外部json测试了它,但它不能用我自己的(所以我假设它是我正在返回的数据)。
作为参考,这是获取和返回JSON的重要部分:
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
return reader.ReadToEnd();
和接口声明:
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string DoWork();
感谢您的时间。
答案 0 :(得分:7)
如果您不希望WCF在您的响应中使用任何格式(即,不将其转换为字符串,这是您当前拥有的字符串),则可以从操作中返回Stream
。这样WCF将按原样返回流上的字节(参见下面的示例代码)。您可以在此帖子中详细了解WCF "Raw" Programming Model。
public class StackOverflow_11342272
{
[ServiceContract]
public class Service
{
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public Stream DoWork()
{
string json = "{\"name\":\"John Doe\",\"age\":33,\"married\":true}";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
return ms;
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress + "/DoWork"));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}