从 RestRequest 获取 zip 文件

Get zip file from RestRequest

对于我使用 RestSharp 的 REST 调用,我必须调用一个服务,该服务必须 return 我将一个 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);”returns“流不支持读取”为错误。 是否有任何设置可以确保它不会 return 出错? 在 Postman 上测试调用我注意到在响应 header 中我有 Content-Disposition 我可以返回文件名吗?

借助 RestSharp 107,您可以使用

var stream = await client.DownloadStreamAsync(request);

它会给你一个流,你可以用它做任何你想做的事。