为什么Web Api HttpResponseMessage没有下载文件?

时间:2015-02-12 19:52:39

标签: asp.net-web-api httpresponse

我目前正在对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
...

1 个答案:

答案 0 :(得分:1)

我不确定,但您可以尝试使用此代码,它对我有用:

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相关的问题。

在下一个链接中,您可以看到如何从javascript客户端使用它: How to download memory stream object via angularJS and webaAPI2

我希望它有所帮助。