[英]How to read application/pdf content type from HttpResponseMessage and convert it into stream
我有一個 Web API 連接到另一個端點。 來自第二個 Web API 的 GET 方法返回應用程序/pdf 內容類型。 在這里,我成功獲取了數據。 如何將 response.Content 轉換為文件/內存 stream 並返回值?
public async Task<T> functionname<T>(ApplicationApiRoutes.APIRoutes route, string token = "", int TimeoutMinutes = 5, CancellationToken cancellationToken = default, params string[] routeparams)
{
T Response = default;
try
{
ApplicationApiRoutes._RouteHashTable.TryGetValue(route, out string FormattedRoute);
FormattedRoute = String.Format(FormattedRoute, routeparams);
using (var request = new HttpRequestMessage(HttpMethod.Get, $"{FormattedRoute}"))
{
if (!String.IsNullOrWhiteSpace(token))
{
request.Headers.Add("Cookie", $"access_token="+ token);
}
using (var response = await _httpclient
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
Response = JsonConvert.DeserializeObject<T>(result, _jsonsettings);
}
}
}
catch (Exception ex)
{
}
return Response;
}
假設您想在檢索文件后下載文件,請在您的 controller 操作方法中嘗試以下操作:
var fileStream = new MemoryStream();
using (var file = await _httpClient.GetStreamAsync(request).ConfigureAwait(false))
{
await file.CopyToAsync(fileStream);
}
fileStream.Position = 0;
return File(fileStream , "application/pdf", "filename.pdf");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.