1

我正在开发 WCF 网络服务。我需要创建一个返回 Json 字符串的 Post 服务,服务声明如下:

[WebInvoke(UriTemplate = "GetMatAnalysis",  ResponseFormat = WebMessageFormat.Json, 
                                                RequestFormat = WebMessageFormat.Json, 
                                                BodyStyle = WebMessageBodyStyle.WrappedRequest, 
                                                Method = "POST")]
string GetMatAnalysis(Stream image);

在此消息中,我使用 using 序列化对象,JavaScriptSerializer().Serialize() 然后将其返回。

但是,当我得到响应时,字符串的开头和结尾有一个额外的双引号。例如我得到:"{"results" : 10 }"而不是{"results" : 10 }

我试图将返回类型更改为System.ServiceModel.Channels.Message出现此错误:

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.

如何让它返回一个没有双引号的 json 字符串?

附加信息:

当我像这样使用 GET 请求时:

[OperationContract(Name = "Messages")]
[WebGet(UriTemplate = "Messages/GetMessage", ResponseFormat = WebMessageFormat.Json)]
Message GetAdvertisment();

返回类型是消息,它工作正常。收到的 Json 字符串是正确的。

任何帮助是极大的赞赏。谢谢

4

2 回答 2

1

由于ResponseFormat = WebMessageFormat.Json,WCF 服务将您返回的对象序列化为 Json。您还使用JavaScriptSerializer().Serialize()并获得双重序列化。

于 2012-08-28T08:42:26.063 回答
0

返回 Stream 而不是字符串,并将传出响应的内容类型设置为“application/json; chatset=utf-8”。这将正确返回所有内容。

界面:

[ServiceContract]
interface ITestService
{        
    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetMatAnalysis")]
    Stream GetMatAnalysis(Stream image);
}

服务:

[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));
    }
}

结果将是:

{"results":10}
于 2019-06-11T06:19:41.687 回答