asp.net webapi实现FileStreamResult
问题
asp.net framework下的webapi没有FileStreamResult,如果想实现和mvc或者.net core下的文件返回需要自己封装实现
创建
新建FileStreamReusltContent.cs
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
using System.Web.Http;namespace FileDownload01.Result
{public class FileStreamReusltContent : IHttpActionResult{private readonly Stream _fileStream;private readonly string _contentType;private readonly string _fileDownloadName;public FileStreamReusltContent(Stream fileStream, string contentType, string fileDownloadName){_fileStream = fileStream;_contentType = contentType;_fileDownloadName = fileDownloadName;}public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken){var response = new HttpResponseMessage(HttpStatusCode.OK);var stream = _fileStream;response.Content = new StreamContent(stream);response.Content.Headers.ContentType = new MediaTypeHeaderValue(_contentType);response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"){FileName = _fileDownloadName};return Task.FromResult(response);}}
}
新建FileReusltContent .cs
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;namespace FileDownload01.Result
{public class FileReusltContent : IHttpActionResult{private readonly string _filePath;private readonly string _contentType;private readonly string _fileDownloadName;public FileReusltContent(string filePath, string contentType, string fileDownloadName){_filePath = filePath;_contentType = contentType;_fileDownloadName = fileDownloadName;}public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken){var response = new HttpResponseMessage(HttpStatusCode.OK);var stream = new FileStream(_filePath, FileMode.Open, FileAccess.Read);response.Content = new StreamContent(stream);response.Content.Headers.ContentType = new MediaTypeHeaderValue(_contentType);response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"){FileName = _fileDownloadName};return Task.FromResult(response);}}
}
使用
[HttpGet]
public IHttpActionResult Get()
{string filePath = HttpContext.Current.Server.MapPath("~/pdf/001.pdf");string contentType = "application/pdf";string fileDownloadName = "001.pdf";//静态文件返回//return new FileReusltContent(filePath, contentType, fileDownloadName);//stream流返回var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);return new FileStreamReusltContent(fileStream, contentType, fileDownloadName);
}