public override async Task <IActionResult> ReturnDownloadActionResultAsync(Guid id, HttpResponse response)
        {
            var doc = await _dataContext.Documents.Where(x => x.ID == id).Select(x => new { x.MimeType, x.FileName, x.Length }).FirstOrDefaultAsync();

            if (doc == null)
            {
                _logger.LogError("Did not find the requested document in the database for the ID {0:D}.", id);
                return(new NotFoundResult());
            }

            _logger.LogDebug("Setting up the Response with Attachment for document ID {0:D}.", id);

            response.ContentType   = "application/octet-stream";
            response.ContentLength = doc.Length;
            var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = doc.FileName,
                Size     = doc.Length
            };

            response.Headers.Add("Content-Disposition", cd.ToString());

            var chunks = GetDocuments(id).ToArray();

            foreach (var chunk in chunks)
            {
                await chunk.DownloadToStreamAsync(response.Body);
            }

            return(new OkResult());
        }
        public HttpResponseMessage Get()
        {
            var    result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            string path   = @"C:\Users\ljudm\source\repos\samples\Files\1.xlsx";
            string path2  = Directory.GetCurrentDirectory() + @"\1.xlsx";

            //Trace.WriteLine(path);
            //Trace.WriteLine(path2);
            Trace.WriteLine(_rootpath);
            //string locationfolder = HttpContext.Current.Server.MapPath("~/Files");
            try
            {
                var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                result.Content = new StreamContent(stream);
                // result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/xlsx");
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                var    value = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                byte[] bytes = System.IO.File.ReadAllBytes(path);

                value.FileName = "1.xlsx";
                result.Content.Headers.ContentDisposition = value;
                return(result);
                // return File(bytes, "application/octet-stream", "1.xlsx");
                // window.open("downloadPage.php");
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.Message);
                result = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
            }
            return(result);
        }
Esempio n. 3
0
        public async Task <IActionResult> ReturnDownloadActionResultAsync(Guid id, HttpResponse response)
        {
            var doc = await _dataContext.Documents.Where(x => x.ID == id).Select(x => new { x.MimeType, x.FileName, x.Length }).FirstOrDefaultAsync();

            if (doc == null)
            {
                _logger.LogError("Did not find the requested document in the database for the ID {0}.", id.ToString("D"));
                return(new NotFoundResult());
            }

            _logger.LogDebug("Setting up the Response with Attachment for ID {0}.", id.ToString("D"));
            response.ContentType   = "application/octet-stream";
            response.ContentLength = doc.Length;
            var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = doc.FileName,
                Size     = doc.Length
            };

            response.Headers.Add("Content-Disposition", cd.ToString());

            var client = new DataLakeAPI(_config);

            var files = await client.ListFiles(id.ToString("D"));

            for (int i = 0; i < files.Count(); i++)
            {
                var file = await client.GetFile(string.Format("{0}_{1}.part", id, i));

                await file.CopyToAsync(response.Body);
            }

            return(new OkResult());
        }
Esempio n. 4
0
        public async Task <string> UploadFirmware(string fileName, Stream binFile)
        {
            CameraInfo.UpdatingFirmware = true;
            try
            {
                string requestStr = String.Format("http://{0}/upgrade_firmware.cgi", CameraInfo.IpAddress);

                var fileContents = new System.Net.Http.StreamContent(binFile);
                fileContents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

                var content = new System.Net.Http.MultipartFormDataContent("---------------------------7deef381d07b6");
                content.Add(fileContents, "file", fileName);

                // override the content disposition
                var contentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
                contentDisposition.Name                 = "file";
                contentDisposition.FileName             = fileName;
                fileContents.Headers.ContentDisposition = contentDisposition;

                return(await PostFormRequest(requestStr, content));
            }
            finally
            {
                // actually, let's wait for next ping to succeed which means the reboot is finished.
                // CameraInfo.UpdatingFirmware = false;
            }
        }
 public ContentDispositionHeaderValue(System.Net.Http.Headers.ContentDispositionHeaderValue containedObject)
 {
     if ((containedObject == null))
     {
         throw new System.ArgumentNullException("containedObject");
     }
     this.containedObject = containedObject;
 }
        internal static void SetFileSettings(string fileName, HttpResponseMessage response, String contentType)
        {
            var mt  = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
            var con = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName
            };

            response.Content.Headers.ContentType        = mt;
            response.Content.Headers.ContentDisposition = con;
        }
Esempio n. 7
0
        public async Task <ActionResult> Get(string fileName)
        {
            var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline")
            {
                FileName = "Excel.xlsx"
            };

            Response.Headers.Add("Content-Disposition", cd.ToString());
            StreamContent stream = YOUR_STREAM_SOURCE
                                   byte[] content = await stream.ReadAsByteArrayAsync();

            return(File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }
Esempio n. 8
0
        public IHttpMultiPartFormDataContentTypeDescriptor WithDisposition(string name, string filename = "")
        {
            var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue(name);

            if (!string.IsNullOrEmpty(filename))
            {
                cd.FileName = filename;
            }

            _httpcontent.Headers.ContentDisposition = cd;

            return(this);
        }
Esempio n. 9
0
        /// <summary>
        /// リクエストにファイルデータを追加します。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="path"></param>
        public void AddFilePart(string name, string path)
        {
            var attachment = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");

            attachment.Name     = name;
            attachment.FileName = System.IO.Path.GetFileName(path);

            var fileContent = new System.Net.Http.StreamContent(System.IO.File.OpenRead(path));

            fileContent.Headers.ContentDisposition = attachment;

            var form = this.GetForm();

            form.Add(fileContent);
        }
        public async Task <IActionResult> ReturnDownloadActionResultAsync(Guid id, HttpResponse response)
        {
            var doc = await _dataContext.Documents.Where(x => x.ID == id).Select(x => new { x.MimeType, x.FileName, x.Length }).FirstOrDefaultAsync();

            if (doc == null)
            {
                _logger.LogError("Did not find the requested document in the database for the ID {0}.", id.ToString("D"));
                return(new NotFoundResult());
            }

            _logger.LogDebug("Setting up the Response with Attachment for ID {0}.", id.ToString("D"));
            response.ContentType   = "application/octet-stream";
            response.ContentLength = doc.Length;
            var cd = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = doc.FileName,
                Size     = doc.Length
            };

            response.Headers.Add("Content-Disposition", cd.ToString());

            var share = GetCloudShare();

            var count = GetDocuments(id).Count();

            _logger.LogDebug("Verifing that the share exists.");
            if (share.Exists())
            {
                for (int i = 0; i < count; i++)
                {
                    CloudFileDirectory rootDir = share.GetRootDirectoryReference();

                    var fileRef = rootDir.GetFileReference(string.Format("{0}_{1}.part", id, i));

                    await fileRef.DownloadToStreamAsync(response.Body);

                    _logger.LogDebug("Added {0}_{1}.part to the Response Stream.", id, i);
                }
            }
            else
            {
                _logger.LogError("The Share specified in the config file does not exists within the Storage Account. The Specified Share in the config file is {0}", _config["Files:FileStorageShare"]);
                throw new Exception("The Share is not configured correctly.");
            }

            return(new OkResult());
        }
Esempio n. 11
0
 public static HttpResponseMessage MultipartFormDataPost(string postUrl, string username, string password, Dictionary <string, object> postParameters)
 {
     using (var client = new HttpClient(new LoggingHandler(new HttpClientHandler())))
     {
         var content = new MultipartFormDataContent();
         foreach (KeyValuePair <string, object> kvp in postParameters)
         {
             if (kvp.Value is List <object> )
             {
                 List <object> lists = (List <object>)kvp.Value;
                 if (lists.Count > 0)
                 {
                     foreach (var f in lists)
                     {
                         var fp = (FileParameter)f;
                         var byteArrayContent = new ByteArrayContent(fp.File);
                         var header           = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
                         header.Name         = fp.FileName;
                         header.FileName     = fp.FileName;
                         header.FileNameStar = null;
                         byteArrayContent.Headers.ContentDisposition = header;
                         byteArrayContent.Headers.Add("Content-Type", "application/octet-stream");
                         content.Add(byteArrayContent);
                     }
                 }
             }
             else
             {
                 var sc = new StringContent((string)kvp.Value);
                 sc.Headers.Clear();
                 content.Add(sc, @"""" + kvp.Key + @"""");
             }
         }
         if (!string.IsNullOrEmpty(username))
         {
             client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password)));
         }
         return(client.PostAsync(postUrl, content).Result);
     }
 }
        public ActionResult UploadImage(int id)
        {
            try
            {
                var    file        = Request.Form.Files[0];
                string folderName  = "Uploads";
                string webRootPath = this.hostingEnvironment.WebRootPath;
                string newPath     = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }

                if (file.Length > 0)
                {
                    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    string fullPath = Path.Combine(newPath, fileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    _ctx.Images.Add(new Image
                    {
                        user_id      = id,
                        content_type = System.IO.Path.GetExtension(fileName).Substring(1),
                        filename     = fileName
                    });
                }

                return(Json("Upload Successful"));
            }
            catch (Exception e)
            {
                return(Json("Upload Failed: " + e.Message));
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Adds the provided images to the current project iteration
        /// </summary>
        /// <param name='projectId'>
        /// The project id.
        /// </param>
        /// <param name='imageData'>
        /// </param>
        /// <param name='tagIds'>
        /// The tags ids to associate with the image batch.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="HttpOperationException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <CreateImageSummaryModel> > CreateImagesFromDataWithHttpMessagesAsync(System.Guid projectId, IEnumerable <Stream> imageData, IList <Guid> tagIds = default(IList <Guid>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (imageData == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "imageData");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("projectId", projectId);
                tracingParameters.Add("tagIds", tagIds);
                tracingParameters.Add("imageData", imageData);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "PostImages", tracingParameters);
            }
            // Construct URL
            var _baseUrl = BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "projects/{projectId}/images/image").ToString();

            _url = _url.Replace("{projectId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(projectId, SerializationSettings).Trim('"')));
            List <string> _queryParameters = new List <string>();

            if (tagIds != null)
            {
                if (tagIds.Count == 0)
                {
                    _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(string.Empty)));
                }
                else
                {
                    foreach (var _item in tagIds)
                    {
                        _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(_item.ToString() ?? string.Empty)));
                    }
                }
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new System.Net.Http.HttpRequestMessage();

            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent();
            if (imageData != null)
            {
                foreach (var image in imageData)
                {
                    System.Net.Http.StreamContent _imageData = new System.Net.Http.StreamContent(image);
                    _imageData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    FileStream _imageDataAsFileStream = image as FileStream;
                    if (_imageDataAsFileStream != null)
                    {
                        System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
                        _contentDispositionHeaderValue.Name     = "imageData";
                        _contentDispositionHeaderValue.FileName = _imageDataAsFileStream.Name;
                        _imageData.Headers.ContentDisposition   = _contentDispositionHeaderValue;
                    }
                    _multiPartContent.Add(_imageData, "imageData");
                }
            }
            _httpRequest.Content = _multiPartContent;
            // Set Credentials
            if (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                if (_httpResponse.Content != null)
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                else
                {
                    _responseContent = string.Empty;
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <CreateImageSummaryModel>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = SafeJsonConvert.DeserializeObject <CreateImageSummaryModel>(_responseContent, DeserializationSettings);
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Esempio n. 14
0
        /// <summary>
        /// Upload file
        /// </summary>
        /// <param name='fileContent'>
        /// File to upload.
        /// </param>
        /// <param name='fileName'>
        /// File name to upload. Name has to be spelled exactly as written here.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <System.IO.Stream> > UploadFileWithHttpMessagesAsync(System.IO.Stream fileContent, string fileName, System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            if (fileContent == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileContent");
            }
            if (fileName == null)
            {
                throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fileName");
            }
            // Tracing
            bool   _shouldTrace  = Microsoft.Rest.ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
                System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>();
                tracingParameters.Add("fileContent", fileContent);
                tracingParameters.Add("fileName", fileName);
                tracingParameters.Add("cancellationToken", cancellationToken);
                Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters);
            }
            // Construct URL
            var _baseUrl = this.Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString();

            // Create HTTP transport objects
            System.Net.Http.HttpRequestMessage  _httpRequest  = new System.Net.Http.HttpRequestMessage();
            System.Net.Http.HttpResponseMessage _httpResponse = null;
            _httpRequest.Method     = new System.Net.Http.HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent();
            if (fileContent != null)
            {
                System.Net.Http.StreamContent _fileContent = new System.Net.Http.StreamContent(fileContent);
                _fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream;
                if (_fileContentAsFileStream != null)
                {
                    System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data");
                    _contentDispositionHeaderValue.Name     = "fileContent";
                    _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name;
                    _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue;
                }
                _multiPartContent.Add(_fileContent, "fileContent");
            }
            if (fileName != null)
            {
                System.Net.Http.StringContent _fileName = new System.Net.Http.StringContent(fileName, System.Text.Encoding.UTF8);
                _multiPartContent.Add(_fileName, "fileName");
            }
            _httpRequest.Content = _multiPartContent;
            // Send Request
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (Newtonsoft.Json.JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new Microsoft.Rest.HttpOperationResponse <System.IO.Stream>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
            }
            if (_shouldTrace)
            {
                Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Esempio n. 15
0
 public static bool TryParse(string input, out System.Net.Http.Headers.ContentDispositionHeaderValue parsedValue)
 {
     throw null;
 }
Esempio n. 16
0
 protected ContentDispositionHeaderValue(System.Net.Http.Headers.ContentDispositionHeaderValue source)
 {
 }
Esempio n. 17
0
        /// <inheritdoc />
        public Task <HttpResponseMessage> TryParse(BasicDeliverEventArgs args)
        {
            _validator.Validate(args);

            try
            {
                var props                    = args.BasicProperties;
                var content                  = new ReadOnlyMemoryContent(args.Body);
                var contentHeaders           = content.Headers;
                var contentTypeHeader        = props.Headers.ExtractHeader(HeaderNames.ContentType);
                var expiresHeader            = props.Headers.ExtractHeader(HeaderNames.Expires);
                var contentDispositionHeader = props.Headers.ExtractHeader(HeaderNames.ContentDisposition);
                var contentMd5Header         = props.Headers.GetOrDefault(HeaderNames.ContentMD5) as byte[];
                props.Headers.Remove(HeaderNames.ContentMD5);
                var contentRangeHeader        = props.Headers.ExtractHeader(HeaderNames.Range);
                var contentLastModifiedHeader = props.Headers.ExtractHeader(HeaderNames.LastModified);
                var contentLocationHeader     = props.Headers.ExtractHeader(HeaderNames.ContentLocation);

                if (!MediaTypeHeaderValue.TryParse(contentTypeHeader, out var mediaType))
                {
                    _log.LogError($"Не удалось распознать заголовок {HeaderNames.ContentType}:{contentTypeHeader}");
                }
                contentHeaders.ContentType = mediaType;

                contentHeaders.Expires            = DateTimeOffset.TryParse(expiresHeader, out var expires) ? expires : (DateTimeOffset?)null;
                contentHeaders.LastModified       = DateTimeOffset.TryParse(contentLastModifiedHeader, out var lastModified) ? lastModified : (DateTimeOffset?)null;
                contentHeaders.ContentRange       = ContentRangeHeaderValue.TryParse(contentRangeHeader, out var contentRange) ? contentRange : null;
                contentHeaders.ContentDisposition = ContentDispositionHeaderValue.TryParse(contentDispositionHeader, out var contentDisposition) ? contentDisposition : null;
                if (Uri.TryCreate(contentLocationHeader, UriKind.RelativeOrAbsolute, out var contentLocation))
                {
                    contentHeaders.ContentLocation = contentLocation;
                }

                if (contentMd5Header != null)
                {
                    contentHeaders.ContentMD5 = contentMd5Header;
                }

                var statusCodeHeader = props.Headers.GetOrDefaultString(HeaderNames.Status);
                props.Headers.Remove(HeaderNames.Status);

                props.Headers.Remove(HeaderNames.ContentLength);

                if (!int.TryParse(statusCodeHeader, out var statusCode))
                {
                    statusCode = DefaultStatusCode;
                }

                var response = new HttpResponseMessage
                {
                    StatusCode = (HttpStatusCode)statusCode,
                    Content    = content
                };
                response.Headers.AddCorrelation(props.CorrelationId);

                foreach (var header in props.Headers)
                {
                    response.Headers.Add(header.Key, ReadHeader(header));
                }

                return(Task.FromResult(response));
            }
            catch (Exception e)
            {
                _log.LogError(e, "Ошибка при парсинге ответа");

                return(null);
            }
        }
 private static bool IsDownloadableFile(System.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition)
 {
     return(contentDisposition != null &&
            !string.IsNullOrEmpty(contentDisposition.FileName));
 }