加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:20:50 所属栏目:百科 来源:网络整理
导读:我正在使用ASP.NET Web API.我想从API(API生成)下载带有C#的PDF. 我可以让API返回一个byte []吗?对于C#应用程序,我可以这样做: byte[] pdf = client.DownloadData("urlToAPI");? 和 File.WriteAllBytes()? 解决方法 最好使用StreamContent返回HttpResponse
我正在使用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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读