WebAPI返回值为文件

2021-03-19 11:25

阅读:529

标签:files   rem   tty   class   media   tput   value   isp   new   

public class FileStreamResult : IHttpActionResult
    {
        readonly Stream _stream;
        readonly string _mediaType = "application/octet-stream";
        readonly string _fileName;
        public FileStreamResult(Stream stream, string fileName)
        {
            _stream = stream;
            _fileName = fileName;
        }

        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute());
        }

        private HttpResponseMessage Execute()
        {
            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                httpResponseMessage.Content = new StreamContent(_stream);
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType);
                httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
                if (!string.IsNullOrEmpty(_fileName))
                {
                    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = HttpUtility.UrlEncode(_fileName, Encoding.UTF8),
                    };
                }
                return httpResponseMessage;
            }
            catch
            {
                httpResponseMessage.Dispose();
                throw;
            }
        }
    }

 

WebAPI返回值为文件

标签:files   rem   tty   class   media   tput   value   isp   new   

原文地址:https://www.cnblogs.com/li-guojiang/p/14554710.html


评论


亲,登录后才可以留言!