【问题标题】:How to save a file to disk from RestSharp through Swagger如何通过 Swagger 从 RestSharp 将文件保存到磁盘
【发布时间】:2020-07-04 02:40:45
【问题描述】:

这个问题与this one 有点相似,我已经使用了大多数公认的解决方案,包括建议的 ResponseTypeFilter。

具体来说,我的 Swagger 控制器如下所示:

    [SwaggerFileResponse(HttpStatusCode.OK, "File Response")]
    [System.Web.Http.HttpGet]
    public void GetFileFromDownloadURL(string r_object_id = null)
    { //Task<Microsoft.Rest.HttpOperationResponse<System.IO.Stream>>?

        try
        {
            DocumentumDownloadFile file = new DocumentumDownloadFile();

            string[] r_object_ids = r_object_id.Split(',');
            foreach (string id in r_object_ids)
            {
                string topUrl = "..." + id.Trim() + "/download-url";
                ApiCall documentumCall = new ApiCall();
                IRestResponse response = documentumCall.ApiCaller(topUrl, false);

                JObject jsonres = JObject.Parse(response.Content);
                JArray array = (JArray)jsonres["entries"];

                string[] stringSeparators = new string[] {"D2"};
                string actual_download_url = "/D2" + array[0]["content"]["url"].ToString().Split(stringSeparators, StringSplitOptions.None)[1];
                ApiCall documentumCall2 = new ApiCall();
                IRestResponse downloadResponse = documentumCall2.ApiCaller(actual_download_url, true);


                File.WriteAllBytes("C:\temp\temp.pdf", downloadResponse.RawBytes);

            }

        }
        catch (Exception e)
        {

            throw new HttpResponseException(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "An Error has occured, try again or  contact the administrator"));

        }

但是,我的代码在最后一个 File.WriteAllbyte 上失败,因为 downloadResponse.RawBytes 为空。这让我感到困惑,因为如果我在 Postman 中运行完全相同的下载 URL 并“另存为文件”,则文件将按预期保存。响应看起来也不错 - 找到了有问题的文件,只是没有传递到 downloadUrl-response。

那么,我想我在 ApiCaller 方法中做了一些不正确的事情,如下所示:

public IRestResponse ApiCaller(string topUrl, bool download)
    {
        string url = "..." + topUrl;
        var client = new RestClient(url)
        {
            Authenticator = new HttpBasicAuthenticator("...", "..")
        };

        var request = new RestRequest(Method.GET);

        request.AddHeader("Accept", "application/json");

        if (download)
        {
            //var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //client.DownloadData(request).SaveAs("C:\temp\temp.pdf");
            //var response = client.DownloadData(request);

            var tempFile = Path.GetTempFileName();
            var stream = File.Create(tempFile, 1024, FileOptions.DeleteOnClose);
            request.ResponseWriter = responseStream => responseStream.CopyTo(stream);
            return client.Execute(request);


        }

        else
        {
            var response = client.Execute(request);
            return response;

        }

    }

如果我删除控制器中的 File.WriteAllbyte,我不会收到任何错误,但只会收到一个响应正文,其中仅包含“[object Blob]”和响应代码 204 No Content。

感谢您朝着正确的方向前进! 谢谢。

【问题讨论】:

    标签: swagger filestream restsharp content-disposition


    【解决方案1】:

    我知道我做错了什么。 response = client.Execute(request); 必须在 request.ResponseWriter = responseStream =&gt; responseStream.CopyTo(stream); 之前运行。然后响应包含字节数据并且可以返回给控制器以获取 File.WriteAllBytes 语句。

    为了这样一个小小的修复工作要花好几个小时......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 2013-12-19
      • 2010-09-23
      • 2010-11-08
      • 1970-01-01
      相关资源
      最近更新 更多