WCF disable chunked Transfer-Encoding

2019-07-25 00:00发布

问题:

I use a restful WCF, and i call a method which has got a stream return type and this is the Response:

HTTP/1.1 200 OK
Cache-Control: private
Transfer-Encoding: chunked
Content-Type: application/octet-stream
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 08 Nov 2013 11:25:29 GMT

6
1;1;

0

I would like to disable the

Transfer-Encoding: chunked

Because it write some plus information what i don't need (6 and 0 in the body)

How can i do it?

回答1:

When you create a WCF endpoint you need to specify what transfer mode (TransferMode) you are using.

  • If it is set to StreamedResponse, Transfer-Encoding: chunked will be added automatically to the response headers, Content-Length will be automatically omitted and there is nothing you can do about that, even if you set the Content-Length explicitly. It is EITHER Content-Length or Transfer-Encoding, they replace each other depending on transfer mode, read this (the first paragraph).
  • If it is set to Buffered, Transfer-Encoding: chunked will be not be added automatically, which will allow Content-Length to be included, if you specify it.

So create your endpoint like this:

WebHttpBinding wb = new WebHttpBinding(WebHttpSecurityMode.Transport);
wb.TransferMode = TransferMode.Buffered; // TransferMode.StreamedResponse;
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(myService.IBlah), blah, "");

I had this problem when I was streaming an MP3 audio from a WCF WebGet and I couldn't see Content-Length. Once your endpoint is configured with Buffered transfer mode, you will start seeing Content-Length.

For me this was only half the battle. In order to properly play MP3 on Chrome, I had to also add Accept-Ranges: bytes to the response headers so that the audio was seekable on Chrome.