[这个问题有点类似于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为null。这使我感到困惑,因为如果我在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组成的响应正文。
我感谢您朝着正确的方向前进!谢谢。
我知道我做错了。 response = client.Execute(request);
必须在request.ResponseWriter = responseStream => responseStream.CopyTo(stream);
之前运行。然后,响应包含字节数据,并且可以将其返回给Controller以执行File.WriteAllBytes语句。
花了这么少的小小工作花了很多时间...