Reputation: 5622
I am trying to write a WCF service (A) that is in turn calling another service (B). This is not a problem. The problem is that B returns json, and this I want to return from A. Here is the code I have:
public class Service1 : IService1
{
public string GetData(int value)
{
WebRequest wr = WebRequest.Create("//url_to_B//");
String username = "user";
String password = "password";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
wr.Headers.Add("Authorization", "Basic " + encoded);
Stream resStream = wr.GetResponse().GetResponseStream();
StreamReader resReader = new StreamReader(resStream);
String response = resReader.ReadToEnd();
resReader.Close();
resStream.Close();
return response;
}
}
and:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
}
Outputs as found in Fiddler:
B:
[{"id":"10103","key":"CAMMOT"}]
A:
"[{\"id\":\"10103\",\"key\":\"CAMMOT\"}]"
The returned value from A if called is a string with data that can be parsed to json. How would I go about returning json instead? Any help appreciated. Thanks.
Upvotes: 0
Views: 181
Reputation:
WCF binding will use jsonSerializer as MessageEncoder if you specify
ResponseFormat = WebMessageFormat.Json
Then it will process string as part of Json object (a property) and encode the " as \" to avoid conflict with the json syntax.
Just remove the ResponseFormat = WebMessageFormat.Json and it should work as you want.
Upvotes: 0
Reputation: 15053
By returning a Stream
, you can return a raw string:
public class Service1 : IService1
{
public System.IO.Stream GetData(int value)
{
WebRequest wr = WebRequest.Create("//url_to_B//");
String username = "user";
String password = "password";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
wr.Headers.Add("Authorization", "Basic " + encoded);
return wr.GetResponse().GetResponseStream();
}
}
Upvotes: 1