private static void SetDownloadFile(ApiDownloadFileResponse downloadFile, Stream stream, IHttpResponse response) { Argument.NotNull(downloadFile, nameof(downloadFile)); Argument.NotNull(stream, nameof(stream)); Argument.NotNull(response, nameof(response)); if (response.StatusCode == HttpStatusCode.OK) { var file = new MemoryStream(); stream.CopyTo(file); file.Position = 0L; downloadFile.File = file; } }
/// <summary> /// Execute request /// </summary> /// <param name="request">The request</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>The response</returns> public async Task <ApiResponse <TResponse> > Execute(ApiRequest <TRequest> request, CancellationToken cancellationToken) { Argument.NotNull(request, nameof(request)); var client = _clientFactory.Create(request); var apiRequest = _requestFactory.Create(request); ApiDownloadFileResponse downloadFile = null; if (request.IsFileDownload == true) { client.ConfigureWebRequest(x => x.AllowReadStreamBuffering = false); downloadFile = new ApiDownloadFileResponse(); apiRequest.AdvancedResponseWriter = (stream, httpResponse) => SetDownloadFile(downloadFile, stream, httpResponse); } _ = apiRequest.AddHeader(HttpRequestHeaderConstants.CacheControl, "no-cache"); if (request.IsFileUpload == true) { client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = false); _ = apiRequest.AddFile( request.UploadFile.ParameterName, request.UploadFile.File.CopyTo, request.UploadFile.FileName, request.UploadFile.Size.Value, request.UploadFile.ContentType); } else { client.ConfigureWebRequest(x => x.AllowWriteStreamBuffering = true); AddBody(request, apiRequest); } var apiResponse = await client .ExecuteAsync <TResponse>(apiRequest, cancellationToken) .ConfigureAwait(Await.Default); var response = new RestSharpApiResponse <TResponse> { RestRequest = apiRequest, RestResponse = apiResponse, IsSuccessful = apiResponse.IsSuccessful, ErrorException = apiResponse.ErrorException, StatusCode = apiResponse.StatusCode, ResponseStatus = _converter.Convert(apiResponse.ResponseStatus) .ThrowIfNoValue() .Value, Content = apiResponse.Content, DownloadFile = downloadFile, }; if (apiResponse.IsSuccessful == true) { response.Model = apiResponse.Data; response.ContentModel = apiResponse.Data; } if (apiResponse.Headers != null) { var headers = apiResponse.Headers .Where(x => x.Type == ParameterType.HttpHeader) .Where(x => x.Value is string) .Select(x => new ResponseHeader { Name = x.Name, Value = x.Value as string }) .ToList(); response.Headers = new ResponseHeaders(headers) { ContentLength = apiResponse.ContentLength, ContentType = apiResponse.ContentType }; SetContentDispositionHeader(response, apiResponse); } return(response); }