There is a self-hosted WCF service with the following contract:
[ServiceContract] interface IMyService { [OperationContract] [WebInvoke(Method = "HEAD", UriTemplate = "Files/{fileName}")] void GetFileInfo(string fileName); [OperationContract] [WebGet(UriTemplate = "Files/{fileName}")] Stream StreamFile(string fileName); } Its simplified implementation is as follows:
class MyService : IMyService { public void GetFileInfo(string fileName) { string filePath = Path.Combine("Files", fileName); FileInfo fi = new FileInfo(filePath); var response = WebOperationContext.Current.OutgoingResponse; response.ContentType = "application/octet-stream"; response.ContentLength = fi.Length; response.StatusCode = HttpStatusCode.OK; response.SuppressEntityBody = true; } public Stream StreamFile(string fileName) { ... } } The problem is in the GetFileInfo method. When a HEAD request to a service occurs (for example, using WebRequest ):
var uri = new Uri("http://localhost:8733/MyService/Files/test.dat"); var req = WebRequest.Create(uri); req.Method = "HEAD"; using (var resp = req.GetResponse() as HttpWebResponse) { Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription); foreach (string header in resp.Headers) Console.WriteLine("{0}: {1}", header, resp.Headers[header]); } then the answer comes:
HTTP/1.1 200 OK Content-Length: 1234 Content-Type: application/octet-stream Date: Wed, 22 Jun 2016 10:17:38 GMT Server: Microsoft-HTTPAPI/2.0 but this is in case the length of the requested file does not exceed int.MaxValue . If the file is longer than int.MaxValue then the Content-Length in the response is 0:
Content-Length: 0 How to win it? How to make return the normal length for large files?
WCF service configuration (if important):
<system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="be_webHttpStreamed"> <webHttp /> </behavior> </endpointBehaviors> </behaviors> <services> <service name="WCFTestService.MyService"> <endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpStreamed" behaviorConfiguration="be_webHttpStreamed" contract="WCFTestService.IMyService" /> <host> <baseAddresses> <add baseAddress="http://localhost:8733/MyService/" /> </baseAddresses> </host> </service> </services> <bindings> <webHttpBinding> <binding name="webHttpStreamed" transferMode="StreamedResponse" /> </webHttpBinding> </bindings> </system.serviceModel>