为什么Web Api HttpResponseMessage 文件下载不了?

Why Web Api HttpResponseMessage not download the file?

我目前正在对 Web Api 方法执行 GET,并将文件名作为参数传递。当我到达该方法时,我的参数已正确解析,并且文件内容正在写入 HttpResponseMessage 对象中的响应内容。

    public HttpResponseMessage Get ([FromUri]string filen)
    {
        string downloadPath = WebConfigurationManager.AppSettings["DownloadLocation"];

        var fileName = string.Format("{0}{1}", downloadPath, filen);
        var response = Request.CreateResponse();

        if (!File.Exists(fileName))
        {
            response.StatusCode = HttpStatusCode.NotFound;
            response.ReasonPhrase = string.Format("The file [{0}] does not exist.", filen);

            throw new HttpResponseException(response);
        }

        response.Content = new PushStreamContent(async (outputStream, httpContent, transportContext) =>
        {
            try
            {
                var buffer = new byte[65536];

                using (var file = File.Open(fileName, FileMode.Open, FileAccess.Read))
                {
                    var length = (int)file.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = file.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }

            }
            finally
            {
                outputStream.Close();
            }

        });

        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = filen
        };

        return response;
    }

没有看到正在下载的文件,似乎什么也没有发生。似乎文件在任何地方都丢失了。我想让浏览器自动下载文件。我确实在 fiddler 中看到了响应中的内容。所以发生了什么事?任何指针将不胜感激!

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/octet-stream
Expires: -1
Server: Microsoft-IIS/8.0
Content-Disposition: attachment; filename=w-brand.png
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcSnVubGlcQXN5bmNGaWxlVXBsb2FkV2ViQVBJRGVtb1xBc3luY0ZpbGVVcGxvYWRXZWJBUElEZW1vXGFwaVxGaWxlRG93bmxvYWQ=?=
X-Powered-By: ASP.NET
Date: Thu, 12 Feb 2015 19:32:33 GMT
27b5
PNG
...

我不确定,但你可以试试这个代码,它对我有用:

result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "SampleImg"; 

可能是与您的 PushStreamContent 相关的问题。

在接下来的 link 中,您可以看到如何从 javascript 客户端使用它:

希望对您有所帮助。