[英]How to get the RestRequest body content after adding file but before sending
[英]Get zip file from RestRequest
對於 REST 調用,我使用 RestSharp,我必須調用一個必須向我返回 zip 文件的服務,然后我將其保存在文件系統上
public bool DownloadZip(int id)
{
while (true)
{
var request = new RestRequest("download/zip", DataFormat.Json);
request.AddHeader("authorization", _token);
request.AddHeader("ID", _id.ToString());
request.AddQueryParameter("id", id.ToString());
var response = new RestClient(url).Get(request);
response.ContentType = "application/zip";
_logFile.Debug($"downloaded result {id}: {response.IsSuccessful} {response.StatusCode}");
if (response.IsSuccessful && !string.IsNullOrWhiteSpace(response.Content))
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
{
using (var zip = File.OpenWrite(path: @"C:\temp\temp.zip"))
{
zip.CopyTo(stream);
}
}
return true;
}
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
_logFile.Warn($"Download Unauthorized {id}: {response.IsSuccessful} {response.StatusCode} {response.Content}");
_authToken = null;
}
else
{
_logFile.Error($"Download {id}: {response.IsSuccessful} {response.StatusCode} {response.Content}");
throw new Exception("DownloadZip Failed");
}
}
}
代碼行“ zip.CopyTo(stream);
”返回“stream 不支持讀取”作為錯誤。 是否有任何設置可以確保它不返回錯誤? 在 Postman 上測試調用我注意到在響應 header 中我有 Content-Disposition ,我可以 go 回到文件名嗎?
使用 RestSharp 107,您可以使用
var stream = await client.DownloadStreamAsync(request);
它會給你一個 stream,你可以用它做任何你想做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.