运维开发网

c# – 如何使用Web API返回文件?

运维开发网 https://www.qedev.com 2020-05-29 10:07 出处:网络 作者:运维开发网整理
我正在使用ASP.NET Web API.我想从API(API生成)下载带有C#的PDF. 我可以让API返回一个byte []吗?对于C#应用程序,我可以这样做: byte[] pdf = client.DownloadData("urlToAPI");? 和 File.WriteAllBytes()? 最好使用StreamContent返回HttpResponseMessage. 这是一个例子
我正在使用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;
}

来自patridge的评论UPD:

如果其他人到这里寻找从字节数组而不是实际文件发出响应,那么您将需要使用新的ByteArrayContent(someData)而不是StreamContent(参见here).

0

精彩评论

暂无评论...
验证码 换一张
取 消