ASP.NETWebAPIを使用しています。
API(APIが生成する)からC#を含むPDFをダウンロードしたい。
APIにを返してもらうことはできますbyte[]
か?C#アプリケーションの場合、次のことができます。
byte[] pdf = client.DownloadData("urlToAPI");?
と
File.WriteAllBytes()?
ASP.NETWebAPIを使用しています。
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 : 他の誰かが実際のファイルではなくバイト配列から応答を送信しようとしている場合は、StreamContent の代わりに new ByteArrayContent(someData) を使用することをお勧めします (こちらを参照)。
についての注意.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");
}