码迷,mamicode.com
首页 > Windows程序 > 详细

WebAPI返回值为文件

时间:2021-03-18 14:44:59      阅读:0      评论:0      收藏:0      [点我收藏+]

标签: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<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult<HttpResponseMessage>(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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!