我正在尝试在我的C#restserviceA中实现一个方法A,它将Json消息返回给客户端。
该方法只是对内部托管服务进行另一次restservice调用,如下面的Say ResterviceB
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "GET";
resp = req.GetResponse() as HttpWebResponse;
resp = req.GetResponse() as HttpWebResponse;
Encoding enc = Encoding.UTF8;
loResponseStream = new StreamReader(resp.GetResponseStream(), enc);
string strResponse = loResponseStream.ReadToEnd();
return resp;
此方法将从RestServiceB以json格式获得响应。我怎么能以json格式将相同的json字符串返回给客户端。
我尝试将webmethod属性如下所示放到我的方法A中,但我从RestServiceA从MethodA获得的响应始终是字符串格式。
SVC界面:
[OperationContract ]
[WebGet(UriTemplate = "getresults", ResponseFormat = WebMessageFormat.Json)]
String GetResults();
SVC代码
public String GetResults()
{
string str=//Call RestServiceB which returns response as below.
"query":"myquery", "results": [ {"name":"result1", "type":"suggest"}, {"name":"result2", "type":"type2"}]"
return str;
}
这里有什么建议吗?谢谢。
答案 0 :(得分:0)
您的JSON字符串被包装在另一个JSON字符串中。
返回原始JSON字符串的一种方法是将GetResults()的输出类型更改为Stream而不是string。
public System.IO.Stream GetResults()
{
string str=//Call RestServiceB which returns response as below.
"query":"myquery", "results": [ {"name":"result1", "type":"suggest"}, {"name":"result2", "type":"type2"}]"
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(str));
}
[OperationContract ]
[WebGet(UriTemplate = "getresults")]
String GetResults();