Llo*_*ell 1 .net c# ajax wcf json
有类似的问题,但它们涉及返回自动解析为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();
Run Code Online (Sandbox Code Playgroud)
和接口声明:
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string DoWork();
Run Code Online (Sandbox Code Playgroud)
感谢您的时间.
如果您不希望WCF在响应中使用任何格式(即,不将其转换为字符串,这是您当前拥有的字符串),则可以Stream从操作中返回a .这样WCF将按原样返回流上的字节(参见下面的示例代码).您可以在这篇文章中阅读有关WCF"原始"编程模型的更多相关信息.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5945 次 |
| 最近记录: |