0

我正在写一个 wcf 网络服务。它将主要关注 json 和 xml,但我需要在 2 种情况下返回字符串。

我正在设置测试:

 [OperationContract]
 [WebInvoke(Method = "GET",
      ResponseFormat = WebMessageFormat.Json,
      BodyStyle = WebMessageBodyStyle.Bare,
      UriTemplate = "test")]
  string BasicString();

我通过自己发送字符串来欺骗响应,绕过标准的 json 返回。

   protected string BasicString()
   {
       string text = "ok";
       HttpResponse response = HttpContext.Current.Response;
       //response.AddHeader("Content-Length", "");
       response.ContentType = "text/html";
       //response.BufferOutput = true;
       response.Output.Write(text);
       //response.ContentEncoding = System.Text.Encoding.UTF8;
       response.End();
       return string.Empty;
   }

大多数浏览器的返回是“OK”。然而,在谷歌浏览器和其他一些浏览器上,它需要最后一个字符。它读作......“O”。我在本地 IIS 上运行它。

如果我把它放在托管的 IIS 上,它会返回“OK”,有时还会返回 329 编码错误。

在所有情况下,我需要从哪里开始寻找它以返回“OK”?

标头?我已经尝试禁用上面的某些行,或者已经禁用了不同的值。

HTTP 嗅探器给了我以下信息: 请求:

GET /Service/Test.svc/string HTTP/1.1 Host: localhost Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8 User-Agent: Mozilla /5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

回复:

HTTP/1.1 200 OK Cache-Control: private Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 内容编码:gzip 变化:接受编码服务器:Microsoft-IIS/8.0 X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET 日期:2013 年 6 月 16 日星期日 12:19 :00 格林威治标准时间

70 �������� I�%&/m�{J�J��t��$ؐ@������iG#)�*��eVe]f@�흼��{���{���;�N'���?\ fdl��J�ɞ!���?~|?"���</p>

4

1 回答 1

1

卡洛斯的评论导致了答案。

使用 IO.stream 作为返回类型,而不是字符串。

[ServiceContract] public class RawService {
    [OperationContract, WebGet]
    public System.IO.Stream GetValue()
    {
        string result = "Hello world";
        byte[] resultBytes = Encoding.UTF8.GetBytes(result);
        return new MemoryStream(resultBytes);
    } }
于 2013-06-17T11:46:23.250 回答