【发布时间】:2021-10-19 00:44:30
【问题描述】:
我正在尝试从存储在 blob 存储中的 Azure 函数流式传输 PDF。这是服务器代码:
[Function("GetPdf")]
public async Task<IActionResult> GetPdf(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")],
HttpRequestData req,
FunctionContext executionContent)
{
// Some code here to validate the body of the request
// Some more code to deserialize the json from the body
var reqBody = await new StreamReader(req.Body).ReadToEndAsynce();
var theRequest = JsonConvert.DeserializeObject<TheRequest>(reqBody);
var result = new ServiceResult<MemoryStream>();
var ms = await svc.GetPdfFromBlobStorage(theRequest.fileName);
ms.Seek(0, SeekOrigin.Begin);
// I've tested that the actual pdf is in fact a pdf
// by saving it to the drive before sending it to the client
return new FileStreamResult(ms, "application/octet-stream");
}
这是客户端代码:
static async Task Main(string[] args)
{
var fileInfo = new FileInfo(@"c:\temp\test.pdf");
var client = new HttpClient();
var req = new { fileName = "the_file"};
var json = JsonConvert.SerializeObject(req);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:7071/api/GetPdf", data);
await using var ms = await response.Content.ReadAsStreamAsync();
await using var fs = File.Create(fileInfo.FullName);
ms.Seek(0, SeekOrigin.Begin);
ms.CopyTo(fs);
}
文件的内容不是pdf,而是纯文本:Microsoft.AspNetCore.Mvc.FileStreamResult
知道我做错了什么,无法在客户端接收流吗?
提前感谢您的帮助
【问题讨论】:
-
ITaskResult是什么?我经常看到IActionResult -
@ESG - 我的错...我修复了读取 IActionResult 的代码。
-
您是否尝试过使用
.ReadAsByteArrayAsync和ByteArrayContent而不是stringContent根据本文档stackoverflow.com/a/46121344 -
代码行
await using var ms = await response.Content.ReadAsStreamAsync();应该是using var ms = await response.Content.ReadAsStreamAsync();吗?
标签: c# azure-functions filestream