Reputation: 10402
I am working on a WCF webservice. I need to create a Post service that returns a Json stringhe service is declared as follows:
[WebInvoke(UriTemplate = "GetMatAnalysis", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
Method = "POST")]
string GetMatAnalysis(Stream image);
in this message I am serializing object with using JavaScriptSerializer().Serialize()
and then return it.
however when I get the responce there is a extra Double-Quote at the start and at the end of the string. For example I am getting: "{"results" : 10 }"
instead of {"results" : 10 }
I tried to change the return type to System.ServiceModel.Channels.Message
I get this error:
An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior contract: http://tempuri.org/:IMyWebServices ----> System.InvalidOperationException: The operation 'GetMatAnalysis' could not be loaded because it has a parameter or return type of type System.ServiceModel.Channels.Message or a type that has MessageContractAttribute and other parameters of different types. When using System.ServiceModel.Channels.Message or types with MessageContractAttribute, the method must not use any other types of parameters.
How can I make it return a json string without the double quotes?
Additional information:
When I use GET request like this:
[OperationContract(Name = "Messages")]
[WebGet(UriTemplate = "Messages/GetMessage", ResponseFormat = WebMessageFormat.Json)]
Message GetAdvertisment();
The return type is message and it works correctly. The Json string received is correct.
Any help is greatly appreciated. Thank you
Upvotes: 1
Views: 2816
Reputation: 156
Return a Stream instead of a string and set the content type of the outgoing response to "application/json; chatset=utf-8". This will return everything properly.
Interface:
[ServiceContract]
interface ITestService
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetMatAnalysis")]
Stream GetMatAnalysis(Stream image);
}
Service:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class TestService : ITestService
{
public Stream GetMatAnalysis(Stream image)
{
MatAnalysisResult matAnalysis = new MatAnalysisResult { results = 10 };
string result = JsonConvert.SerializeObject(matAnalysis);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(result));
}
}
The result will be:
{"results":10}
Upvotes: 0
Reputation: 116108
Since ResponseFormat = WebMessageFormat.Json
, WCF service serializes your returned object as Json. You also use JavaScriptSerializer().Serialize()
and you get double serialization.
Upvotes: 1