【发布时间】: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