我正在使用ASP.NET Web API.我想从API(API生成)下载带有C#的PDF. 我可以让API返回一个byte []吗?对于C#应用程序,我可以这样做: byte[] pdf = client.DownloadData("urlToAPI");? 和 File.WriteAllBytes()? 最好使用
我可以让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;
}
来自patridge的评论UPD:
如果其他人到这里寻找从字节数组而不是实际文件发出响应,那么您将需要使用新的ByteArrayContent(someData)而不是StreamContent(参见here).
