예제 #1
0
        public async Task InvokeAsync(HttpContext context)
        {
            var result = await _storage.TryGetDetailByIdAsync(context.Request.Query["id"]);

            var resultBody = await _storage.TryGetResponseBodyByIdAsync(context.Request.Query["id"]);

            var entry = result.Value;

            if (!result.Succeed || !resultBody.Succeed || entry == null)
            {
                context.Response.StatusCode = 404;
                return;
            }

            var contentType = (entry.ResponseHeaders != null)
                ? entry.ResponseHeaders.TryGetValue("Content-Type", out var headers)
                    ? headers.FirstOrDefault()
                    : "application/octet-stream"
                : "application/octet-stream";

            context.Response.ContentType = "application/octet-stream";
            context.Response.StatusCode  = 200;
            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(entry.Id + FileNameHelper.GetExtension(entry.Path, contentType));
            context.Response.GetTypedHeaders().ContentDisposition = contentDisposition;
            await context.Response.Body.WriteAsync(resultBody.Value ?? Array.Empty <byte>(), 0, resultBody.Value?.Length ?? 0);
        }
예제 #2
0
        public async Task ExecuteResultAsync(ActionContext context)
        {
            context.HttpContext.Response.ContentType = _contentType;

            if (_stream.CanSeek)
            {
                context.HttpContext.Response.ContentLength = _stream.Length;
            }

            if (!string.IsNullOrWhiteSpace(_fileDownloadName))
            {
                ContentDispositionHeaderValue dispositionHeaderValue = new ContentDispositionHeaderValue("attachment");
                dispositionHeaderValue.SetHttpFileName(_fileDownloadName);

                context.HttpContext.Response.Headers["Content-Disposition"] = dispositionHeaderValue.ToString();
            }

            Stream body = context.HttpContext.Response.Body;

            try {
                await _stream.CopyToAsync(body, _bufferSize);
            }

            finally {
                _stream.Dispose();
            }
        }
예제 #3
0
        public async Task ExecuteResultAsync(ActionContext context)
        {
            HttpResponse response = context.HttpContext.Response;

            // Set response content type
            response.ContentType = "text/csv";

            // Set content disposition to make this a download
            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(_fileDownloadName);
            response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();

            try
            {
                // Write CSV records to response stream
                await using var streamWriter = new StreamWriter(response.Body, Encoding.UTF8, 1024, true);
                await foreach (string record in _records)
                {
                    await streamWriter.WriteLineAsync(record);
                }
            }
            catch (OperationCanceledException)
            {
                // Don't throw this exception, it's most likely caused by the client disconnecting.
                // However, if it was cancelled for any other reason we need to prevent empty responses.
                context.HttpContext.Abort();
            }
        }
예제 #4
0
        public async Task ExecuteAsync(ActionContext context, FileCallbackResult result)
        {
            try
            {
                SetHeadersAndLog(context, result, null, false);

                if (!string.IsNullOrWhiteSpace(result.FileDownloadName) && result.SendInline)
                {
                    var headerValue = new ContentDispositionHeaderValue("inline");

                    headerValue.SetHttpFileName(result.FileDownloadName);

                    context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = headerValue.ToString();
                }

                await result.Callback(context.HttpContext.Response.Body);
            }
            catch (Exception e)
            {
                if (!context.HttpContext.Response.HasStarted && result.Send404)
                {
                    context.HttpContext.Response.Headers.Clear();
                    context.HttpContext.Response.StatusCode = 404;

                    Logger.LogCritical(new EventId(99), e, "Failed to send result.");
                }
                else
                {
                    throw;
                }
            }
        }
        private async Task RenderReturnedFile(IHttpContext context, IReturnedFileStorage returnedFileStorage)
        {
            const string         attachmentDispositionType = "attachment";
            ReturnedFileMetadata metadata;

            var id = Guid.Parse(context.Request.Query["id"]);

            using (var stream = returnedFileStorage.GetFile(id, out metadata))
            {
#if DotNetCore
                var contentDispositionValue = new ContentDispositionHeaderValue(attachmentDispositionType);
                contentDispositionValue.SetHttpFileName(metadata.FileName);
                context.Response.Headers[HeaderNames.ContentDisposition] = contentDispositionValue.ToString();
#else
                var contentDispositionValue = new ContentDispositionHeaderValue(attachmentDispositionType)
                {
                    FileName     = metadata.FileName,
                    FileNameStar = metadata.FileName
                };
                context.Response.Headers["Content-Disposition"] = contentDispositionValue.ToString();
#endif
                context.Response.ContentType = metadata.MimeType;
                if (metadata.AdditionalHeaders != null)
                {
                    foreach (var header in metadata.AdditionalHeaders)
                    {
                        context.Response.Headers.Add(new KeyValuePair <string, string[]>(header.Key, header.Value));
                    }
                }

                context.Response.StatusCode = (int)HttpStatusCode.OK;
                await stream.CopyToAsync(context.Response.Body);
            }
        }
        /// <inheritdoc />
        public override async Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var bufferingFeature = context.HttpContext.Features.Get <IHttpBufferingFeature>();

            bufferingFeature?.DisableResponseBuffering();

            context.HttpContext.Response.ContentType = ContentType;

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                var header = new ContentDispositionHeaderValue("attachment");
                header.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers["Content-Disposition"] = header.ToString();
            }

            Console.WriteLine("Executing FileResult, sending file as {0}", FileDownloadName);

            try
            {
                await _callback(context.HttpContext.Response.Body, context);
            }
            catch (IOException ex) when(ex.InnerException is SocketException)
            {
                var sex = (SocketException)ex.InnerException;

                Console.WriteLine("{0}: {1}, {2}", ex.Message, sex.ErrorCode, sex.SocketErrorCode);
            }
        }
예제 #7
0
        public override void WriteResponseHeaders(OutputFormatterWriteContext context)
        {
            base.WriteResponseHeaders(context);

            var    response    = context.HttpContext.Response;
            var    elementType = _elementType(context.ObjectType) ?? context.ObjectType;
            string fileName;

            var excelDocumentAttribute = ReflectionHelper.GetAttribute <ExcelDocumentAttribute>(elementType);

            if (excelDocumentAttribute != null && !string.IsNullOrEmpty(excelDocumentAttribute.FileName))
            {
                // If attribute exists with file name defined, use that.
                fileName = excelDocumentAttribute.FileName;
            }
            else
            {
                fileName = elementType.Name;
            }

            if (!fileName.EndsWith("xlsx", StringComparison.CurrentCultureIgnoreCase))
            {
                fileName += ".xlsx";
            }

            var cd = new ContentDispositionHeaderValue("attachment");

            cd.SetHttpFileName(fileName);
            response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
        }
예제 #8
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            var remoteStream = (IRemoteStreamContent)context.Object;

            if (remoteStream != null)
            {
                context.HttpContext.Response.ContentType = remoteStream.ContentType;

                if (!remoteStream.FileName.IsNullOrWhiteSpace())
                {
                    var contentDisposition = new ContentDispositionHeaderValue("attachment");
                    contentDisposition.SetHttpFileName(remoteStream.FileName);
                    context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
                }

                using (var stream = remoteStream.GetStream())
                {
                    if (stream.CanSeek)
                    {
                        stream.Position = 0;
                    }

                    await stream.CopyToAsync(context.HttpContext.Response.Body);
                }
            }
        }
    public void SetHttpFileName_ShouldSanitizeFileNameWhereNeeded(string httpFileName, string expectedFileName)
    {
        var contentDisposition = new ContentDispositionHeaderValue("inline");

        contentDisposition.SetHttpFileName(httpFileName);
        Assert.Equal(expectedFileName, contentDisposition.FileName);
    }
예제 #10
0
        /// <inheritdoc />
        public override Task ExecuteResultAsync([NotNull] ActionContext context)
        {
            var response = context.HttpContext.Response;

            if (ContentType != null)
            {
                response.ContentType = ContentType;
            }

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                var cd = new ContentDispositionHeaderValue("attachment");
                cd.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers.Set(HeaderNames.ContentDisposition, cd.ToString());
            }

            // We aren't flowing the cancellation token appropriately, see
            // https://github.com/aspnet/Mvc/issues/743 for details.
            return(WriteFileAsync(response, CancellationToken.None));
        }
예제 #11
0
        public async Task WriteAsync(HttpContext context)
        {
            context.Response.StatusCode = 200;

            if (string.IsNullOrEmpty(ContentType))
            {
                var ext = string.IsNullOrEmpty(FileName) ? ".unknown" : System.IO.Path.GetExtension(FileName);
                ContentType = MimeTypeMap.GetMimeType(ext);
            }

            context.Response.ContentType = ContentType;

            if (Stream.CanSeek)
            {
                Stream.Seek(0, System.IO.SeekOrigin.Begin);
                context.Response.ContentLength = Stream.Length;
            }

            if (!string.IsNullOrEmpty(FileName))
            {
                var contentDisposition = new ContentDispositionHeaderValue("attachment");
                contentDisposition.SetHttpFileName(FileName);
                context.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }



            var outputStream = context.Response.Body;

            using (Stream)
            {
                await Stream.CopyToAsync(outputStream);
            }
        }
예제 #12
0
        /// <inheritdoc />
        public override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var loggerFactory = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger <FileResult>();

            var response = context.HttpContext.Response;

            response.ContentType = ContentType.ToString();

            if (!string.IsNullOrEmpty(FileDownloadName))
            {
                // From RFC 2183, Sec. 2.3:
                // The sender may want to suggest a filename to be used if the entity is
                // detached and stored in a separate file. If the receiving MUA writes
                // the entity to a file, the suggested filename should be used as a
                // basis for the actual filename, where possible.
                var contentDisposition = new ContentDispositionHeaderValue("attachment");
                contentDisposition.SetHttpFileName(FileDownloadName);
                context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }

            logger.FileResultExecuting(FileDownloadName);
            return(WriteFileAsync(response));
        }
예제 #13
0
        public async Task <IActionResult> Download(Guid tileCacheId)
        {
            TileCache tileCache = await TileCacheRepository.GetTileCacheWithId(tileCacheId);

            if (tileCache == null)
            {
                return(NotFound());
            }

            string path = Path.Combine(ServiceOptions.DirectoryRoot, "TileCaches", tileCache.Filename);

            if (!System.IO.File.Exists(path))
            {
                return(NotFound());
            }

            // Set up the content-disposition header with proper encoding of the filename
            ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(tileCache.Filename);
            Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();

            FileStream stream = new FileStream(path, FileMode.Open);

            return(new FileStreamResult(stream, @"application/octet-stream"));
        }
        public void DownloadDemandAggregation(DemandAggregationSearchItems search)
        {
            FileExtensions ext      = FileExtensions.xlsx;
            var            workBook = dashboardHandler.GetDemandAggregationReportData(search, ext);

            string fileExtension = string.Empty;

            switch (ext)
            {
            case FileExtensions.xlsx:
                fileExtension = $".{FileExtensions.xlsx.ToString()}";
                break;

            case FileExtensions.xls:
                fileExtension = $".{FileExtensions.xls.ToString()}";
                break;
            }
            var response = HttpContext.Response;

            response.ContentType = FileTypes.MimeTypes[fileExtension];
            var contentDisposition =
                new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(
                string.Format("{0}{1}", DateTime.Now.Ticks, fileExtension));
            response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            workBook.Write(response.Body);
        }
    public void FileNameWithSurrogatePairs_EncodedCorrectly()
    {
        var contentDisposition = new ContentDispositionHeaderValue("attachment");

        contentDisposition.SetHttpFileName("File 🤩 name.txt");
        Assert.Equal("File __ name.txt", contentDisposition.FileName);
        Assert.Equal(2, contentDisposition.Parameters.Count);
        Assert.Equal("UTF-8\'\'File%20%F0%9F%A4%A9%20name.txt", contentDisposition.Parameters[1].Value);
    }
예제 #16
0
 private static void SetContentDispositionHeader(ActionContext context, FileResult result)
 {
     if (!string.IsNullOrEmpty(result.FileDownloadName))
     {
         var contentDisposition = new ContentDispositionHeaderValue("attachment");
         contentDisposition.SetHttpFileName(result.FileDownloadName);
         context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     }
 }
예제 #17
0
        public void GetHeaderValue_Produces_Correct_ContentDisposition(string input, string expectedOutput)
        {
            // Arrange & Act
            var cd = new ContentDispositionHeaderValue("attachment");

            cd.SetHttpFileName(input);
            var actual = cd.ToString();

            // Assert
            Assert.Equal(expectedOutput, actual);
        }
예제 #18
0
        public override void WriteResponseHeaders(OutputFormatterWriteContext context)
        {
            var data     = (CampaignStatistics)context.Object;
            var response = context.HttpContext.Response;

            response.ContentType = FileExtensions.GetMimeType("xlsx");
            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            _utcNow = DateTime.UtcNow;
            contentDisposition.SetHttpFileName($"{data.Title.ToLower()}_{_utcNow:yyyyMMddHHmm}.xlsx");
            response.Headers.Add(HeaderNames.ContentDisposition, contentDisposition.ToString());
        }
            public async override Task ExecuteResultAsync(ActionContext context)
            {
                await Content(context.HttpContext.Response.Body, (filename, contentType, length, open) =>
                {
                    var contentDisposition = new ContentDispositionHeaderValue(open ? "inline" : "attachment");
                    contentDisposition.SetHttpFileName(filename);

                    context.HttpContext.Response.ContentLength = length;
                    context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
                    context.HttpContext.Response.ContentType = contentType;
                });
            }
예제 #20
0
        private async Task ReadTypeDefinitions(ResourceExecutingContext context)
        {
            var        actionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor;
            MethodInfo actionMethod     = actionDescriptor.MethodInfo;

            MemoryStream memoryStream = await _resourceReader.ReadTypeDefinitionFiles(actionMethod);

            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName("resource-types.ts");
            context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();

            context.Result = new FileStreamResult(memoryStream, new MediaTypeHeaderValue("text/plain"));
        }
        /// <summary>
        /// Sets content disposition as inline when there is no file download name specified.
        /// </summary>
        /// <param name="context">
        /// The action context.
        /// </param>
        /// <param name="result">
        /// The <see cref="IResumingFileResult"/>.
        /// </param>
        public static void SetContentDispositionHeaderInline(ActionContext context, IResumingFileResult result)
        {
            if (string.IsNullOrEmpty(result.FileDownloadName))
            {
                var contentDisposition = new ContentDispositionHeaderValue("inline");

                if (!string.IsNullOrWhiteSpace(result.FileInlineName))
                {
                    contentDisposition.SetHttpFileName(result.FileInlineName);
                }

                context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }
        }
 private void SetContentDispositionHeader(ActionContext context, FileResult result)
 {
     if (!string.IsNullOrEmpty(result.FileDownloadName))
     {
         // From RFC 2183, Sec. 2.3:
         // The sender may want to suggest a filename to be used if the entity is
         // detached and stored in a separate file. If the receiving MUA writes
         // the entity to a file, the suggested filename should be used as a
         // basis for the actual filename, where possible.
         var contentDisposition = new ContentDispositionHeaderValue("attachment");
         contentDisposition.SetHttpFileName(result.FileDownloadName);
         context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
     }
 }
        /// <summary>
        /// 设置响应头ContentDispositionHeader
        /// </summary>
        /// <param name="context"></param>
        /// <param name="result"></param>
        private void SetContentDispositionHeaderInline(ActionContext context, IResumeFileResult result)
        {
            context.HttpContext.Response.Headers[HeaderNames.AccessControlExposeHeaders] = HeaderNames.ContentDisposition;
            if (string.IsNullOrEmpty(result.FileDownloadName))
            {
                var contentDisposition = new ContentDispositionHeaderValue("inline");

                if (!string.IsNullOrWhiteSpace(result.FileInlineName))
                {
                    contentDisposition.SetHttpFileName(result.FileInlineName);
                }

                context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }
        }
        /// <summary>
        /// sets up the response
        /// </summary>
        public async override Task ExecuteResultAsync(ActionContext context)
        {
            var response = context.HttpContext.Response;

            response.ContentType = ContentType;
            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(FileDownloadName);
            response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            response.StatusCode = StatusCodes.Status200OK;
            using (_fileStream)
            {
                await StreamCopyOperation.CopyToAsync(_fileStream, response.Body, null, context.HttpContext.RequestAborted);
            }
            File.Delete(_filePath);
        }
        public void SetResponseHeaders(HttpResponse response, FileDownloadResViewModel fileInfo, string contentType, long fileLength, string fileName)
        {
            response.Headers[HeaderNames.AcceptRanges] = "bytes";
            response.StatusCode = fileInfo.IsPartial ? StatusCodes.Status206PartialContent
                                      : StatusCodes.Status200OK;

            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(fileName);
            response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            response.Headers[HeaderNames.ContentType]        = contentType;
            response.Headers[HeaderNames.ContentLength]      = fileInfo.Length.ToString();
            if (fileInfo.IsPartial)
            {
                response.Headers[HeaderNames.ContentRange] = new ContentRangeHeaderValue(fileInfo.From, fileInfo.To, fileLength).ToString();
            }
        }
예제 #26
0
        /// <summary>
        /// 设置响应头信息
        /// </summary>
        /// <param name="response"></param>
        /// <param name="partialFileInfo"></param>
        /// <param name="fileLength"></param>
        /// <param name="fileName"></param>
        private void SetResponseHeaders(HttpResponse response, PartialFileInfo partialFileInfo)
        {
            response.Headers[HeaderNames.AcceptRanges] = "bytes";
            response.StatusCode = partialFileInfo.IsPartial ? StatusCodes.Status206PartialContent : StatusCodes.Status200OK;

            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(partialFileInfo.Name);
            response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            response.Headers[HeaderNames.ContentType]        = "application/octet-stream";
            //response.Headers[HeaderNames.ContentMD5] = partialFileInfo.MD5;
            response.Headers[HeaderNames.ContentLength] = partialFileInfo.Length.ToString();
            if (partialFileInfo.IsPartial)
            {
                response.Headers[HeaderNames.ContentRange] = new ContentRangeHeaderValue(partialFileInfo.From, partialFileInfo.To, partialFileInfo.FileLength).ToString();
            }
        }
예제 #27
0
        public async Task <ActionResult> File(int assetId, string fileName, string extension)
        {
            var file = await GetFile(assetId);

            if (file == null)
            {
                return(FileAssetNotFound("File not found"));
            }

            // Set the filename header separately to force "inline" content
            // disposition even though a filename is specified.
            var contentDisposition = new ContentDispositionHeaderValue("inline");

            contentDisposition.SetHttpFileName(file.FileName);
            Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();

            return(File(file.ContentStream, file.ContentType));
        }
예제 #28
0
        public override void WriteResponseHeaders(OutputFormatterWriteContext context)
        {
            base.WriteResponseHeaders(context);

            if (context.Object is Hl7.Fhir.Model.Binary binary)
            {
                var contentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = String.Format("fhir_binary_{0}_{1}.{2}",
                                             binary.Id,
                                             binary.Meta != null ? binary.Meta.VersionId : "0",
                                             GetFileExtensionForMimeType(binary.ContentType))
                };

                contentDisposition.SetHttpFileName(contentDisposition.FileName);
                context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            }
        }
        public virtual IActionResult GetFile(Guid id)
        {
            IFile file = this.fileService.GetFile(id);

            if (file == null)
            {
                return(NotFound());
            }

            var contentDisposition = new ContentDispositionHeaderValue("attachment");

            contentDisposition.SetHttpFileName(file.FileName);
            //Fix for Swagger UI
            contentDisposition.FileName = contentDisposition.FileName.Replace('?', '_').Replace(' ', '_').Replace("\"", "");
            Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
            //Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition, Transfer-Encoding");

            return(File(file.Bytes, "application/octet-stream"));
        }
예제 #30
0
        public void DownloadTemplate()
        {
            string filePath =
                Path.Combine(hostingEnvironment.WebRootPath, "Templates/BulkJobSeekerTemplates/BulkJobSeekers.xlsx");

            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                HttpContext.Response.ContentType = "application/vnd.ms-excel";

                ContentDispositionHeaderValue contentDisposition =
                    new ContentDispositionHeaderValue("attachment");

                contentDisposition.SetHttpFileName(
                    string.Format("{0}.xlsx", DateTime.Now.Ticks));

                HttpContext.Response.Headers[HeaderNames.ContentDisposition]
                    = contentDisposition.ToString();
                stream.CopyTo(HttpContext.Response.Body);
            }
        }