如何使用Web API返回文件? [英] How to return a file using Web API?

查看:308
本文介绍了如何使用Web API返回文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using ASP.NET Web API.
I want to download a PDF with C# from the API (that the API generates).

我可以让API返回byte[]吗?对于C#应用程序,我可以这样做:

Can I just have the API return a byte[]? and for the C# application can I just do:

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

File.WriteAllBytes()?

推荐答案

最好返回其中带有StreamContent的HttpResponseMessage.

Better to return HttpResponseMessage with StreamContent inside of it.

以下是示例:

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 来自 pattern 的评论: 如果其他任何人希望从字节数组而不是实际文件中发送响应,则您将要使用新的ByteArrayContent(someData)而不是StreamContent(请参阅

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

这篇关于如何使用Web API返回文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆