gpt4 book ai didi

c# - 从 C# 中的 REST 服务下载文件

转载 作者:行者123 更新时间:2023-12-05 02:51:05 28 4
gpt4 key购买 nike

我正在尝试将文件保存到客户端的机器上。我想要求客户端选择下载位置。

我有 REST 服务端点,它返回要下载的文件。我正在尝试设置代码以下载使用另存为对话框从服务返回的文件。

            var Url = "https://randomaddresss/v5/invoices/{" + InvoicesId + "}/getpdfbyid";

HttpResponse response = HttpContext.Current.Response;

response.ClearContent();
response.Clear();

response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + InvoicesId + ".pdf;");

response.TransmitFile(Url);

response.Flush();
response.End();

返回的错误在 response.TransmitFile(Url); 行:

'https:/randomaddresss/v5/invoices/2131231231231312/getpdfbyid'is not a valid virtual path.

最佳答案

HttpResponse.TransmitFile 需要文件路径,而不是 URL。

您需要先下载文件,然后写入响应流。

这是一个使用 HttpClient 的例子:

using var invoiceResponse = await httpClient.GetAsync(Url);
using var invoiceStream = await invoiceResponse.Content.ReadAsStreamAsync();

invoiceStream.CopyTo(response.OutputStream);

response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + InvoicesId + ".pdf;");

关于c# - 从 C# 中的 REST 服务下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63396039/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com