微软Web Api返回一个文件? 使用byte ?

我正在使用ASP.NET Web API
我想从API(即API生成)用C#下载PDF。

我可以只有API返回一个byte[] ? 而对于C#应用程序,我可以做:

 byte[] pdf = client.DownloadData("urlToAPI");? 

 File.WriteAllBytes()? 

最好用StreamContent将HttpResponseMessage返回。

这里是例子:

 public HttpResponseMessage GetFile(string id) { if (String.IsNullOrEmpty(id)) return Request.CreateResponse(HttpStatusCode.BadRequest); string fileName; string localFilePath; int fileSize; localFilePath = getFileFromID(id, out fileName, out fileSize); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read)); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = fileName; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return response; } 

UPD来自patridge的评论:如果有人想要发送一个字节数组而不是一个实际的文件的响应,你会想要使用新的ByteArrayContent(someData),而不是StreamContent(见这里 )。

我做了以下的行动:

 [HttpGet] [Route("api/DownloadPdfFile/{id}")] public HttpResponseMessage DownloadPdfFile(long id) { HttpResponseMessage result = null; try { SQL.File file = db.Files.Where(b => b.ID == id).SingleOrDefault(); if (file == null) { result = Request.CreateResponse(HttpStatusCode.Gone); } else { // sendo file to client byte[] bytes = Convert.FromBase64String(file.pdfBase64); result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new ByteArrayContent(bytes); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = file.name + ".pdf"; } return result; } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.Gone); } }