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; } } }