117

ASP.NETWebAPIを使用しています。
API(APIが生成する)からC#を含むPDFをダウンロードしたい。

APIにを返してもらうことはできますbyte[]か?C#アプリケーションの場合、次のことができます。

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

File.WriteAllBytes()?
4

7 に答える 7

187

その中に 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 : 他の誰かが実際のファイルではなくバイト配列から応答を送信しようとしている場合は、StreamContent の代わりに new ByteArrayContent(someData) を使用することをお勧めします (こちらを参照)。

于 2012-06-20T18:20:08.890 に答える
28

についての注意.Net Core: raw バイトを送信する場合は、を使用しFileContentResultて contentType を に設定できます。application/octet-stream例:

[HttpGet("{id}")]
public IActionResult GetDocumentBytes(int id)
{
    byte[] byteArray = GetDocumentByteArray(id);
    return new FileContentResult(byteArray, "application/octet-stream");
}
于 2019-07-03T17:55:33.003 に答える