proudmonkey / AutoWrapper

A simple, yet customizable global exception handler and Http response wrapper for ASP.NET Core APIs.
MIT License
679 stars 82 forks source link

File Response got corrupted due to Content-Type was always application/json #117

Closed RajaduraiAz closed 3 years ago

RajaduraiAz commented 3 years ago

Returning FileStreamResult got corrupted file due to Content-Type always returning as "application/json"

proudmonkey commented 3 years ago

Hi, You should decorate your action method with [AutoWrapIgnore] when returning FileStreamResult.

Sample Usage:

        [HttpGet("getfile")]
        [AutoWrapIgnore]
        public FileStreamResult GetFile2()
        {
            var filePath = $"{Environment.CurrentDirectory}/Logs/log_20200501.txt";
            var file = System.IO.File.OpenRead(filePath);
            var provider = new FileExtensionContentTypeProvider();
            var fileInfo = new System.IO.FileInfo(filePath);
            var memi = provider.Mappings[fileInfo.Extension];
            return File(file, memi, fileInfo.Name);
        }

        [HttpGet("getfile2")]
        [AutoWrapIgnore]
        public FileStreamResult GetFile()
        {
            var path = $"{Environment.CurrentDirectory}/Logs/log_20200501.txt";
            var stream = System.IO.File.OpenRead(path);
            return new FileStreamResult(stream, "application/octet-stream");
        }

        [HttpGet("getpdf")]
        [AutoWrapIgnore]
        public IActionResult GetPdf()
        {
            var path = $"{Environment.CurrentDirectory}/sample.pdf";
            byte[] fileBytes = System.IO.File.ReadAllBytes(path);
            return new FileContentResult(fileBytes, "application/pdf");
        }

        [HttpGet("getpdf2")]
        [AutoWrapIgnore]
        public IActionResult GetPdf2()
        {
            var path = $"{Environment.CurrentDirectory}/sample.pdf";
            var stream = new FileStream(path, FileMode.Open);
            return new FileStreamResult(stream, "application/pdf");
        }

        //returns text/plain
        [HttpGet("getstring")]
        [AutoWrapIgnore]
        public ContentResult GetString()
        {
            return Content("Hello");
        }