WCF服务总是在响应正文中返回随机数

本文关键字:正文 返回 随机数 响应 服务 WCF | 更新日期: 2023-09-27 17:59:44

我有一个用C#编写的WCF服务:

namespace MyServices
{
    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/foo/{param}")]
        string foo(string param);
    }
}
public class MyService : IMyService
{
    public string foo(string param)
    {
        //Do stuff with param
        return "Some processed data";
    }
}

每当我使用此服务时,它都能正常工作,除了响应中的每一行前面总是有一个数字(有时是一个带字符的数字)。最后一行总是0。

下面是一个使用Java编写的服务的客户端:

public class Main
{
    public static void main(String[] args)
    {
        try 
        {
            Socket soc = new Socket(InetAddress.getByName("<SOME IP ADDRESS>"), 80);
            PrintWriter out = new PrintWriter(soc.getOutputStream());
            String headers = "GET /MyService.svc/foo/some_data HTTP/1.1'r'n"
                             + "Host: <SOME HOST>'r'n"
                             + "Content-Type: text/plain;charset=utf-8'r'n"
                             + "Content-Length: 0'r'n'r'n";
            out.print(headers);
            out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
            String response;
            while((response = in.readLine())!=null)
            {
                //Do something with the response            
                System.out.println(response);
            }
            out.close();
            soc.close();
        catch (UnknownHostException e) 
        {
            System.err.println(e.getMessage());
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

这将输出以下内容:

HTTP/1.1 200 OK
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: text/plain;charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=2e5dd814a4cb78f8a5825d56c5879cd18fa384d20597b10f3c685ffe2cff1f53;Path=/;Domain=<SOME DOMAIN NAME>
Date: Tue, 02 Aug 2016 22:53:25 GMT
15
"Some processed data"
0

起初,我认为数字表示下一行中的字符数,0表示消息正文的末尾,但事实并非如此。

感谢您的帮助:)

WCF服务总是在响应正文中返回随机数

这是因为传输编码是分块的(https://en.wikipedia.org/wiki/Chunked_transfer_encoding)。15是十六进制的,表示该块中的21个字符,0作为结束标记。