我可以使用MVC4的ApiController实现文件下载吗?

时间:2012-08-18 00:06:28

标签: asp.net-mvc-4

使用常规控制器我可以通过返回FileResult来完成。这似乎不适用于ApiController。可以吗?它甚至是正确的事情吗?

2 个答案:

答案 0 :(得分:6)

试试这个。

[HttpGet]    
public HttpResponseMessage Get()
    {
        var file = HttpContext.Current.Server.MapPath("~/Images/accent.png");
        var stream = new FileStream(file, FileMode.Open);
        var content = new HttpResponseMessage(HttpStatusCode.OK)
                         {
                             Content = new StreamContent(stream)
                         };
        content.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return content;
    }

答案 1 :(得分:4)

我的工作归功于this question

using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;

namespace Web.Controllers
{
    //usage: /download/report

    [RoutePrefix("download")]
    public class DownloadController : ApiController
    {
        [HttpGet("report")]
        public HttpResponseMessage Report()
        {
            using (var service = new Client())
            {
                var report = service.BuildReport();

                return DownloadResponse(report, "Report.csv");
            }
        }

        private static HttpResponseMessage DownloadResponse(string content, string fileName)
        {
            var downloadContent = new StringContent(content);

            var mediaType = new MediaTypeHeaderValue("application/octet-stream");
            var disposition= new ContentDispositionHeaderValue("attachment") { FileName = fileName };

            downloadContent.Headers.ContentType = mediaType;
            downloadContent.Headers.ContentDisposition = disposition;

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = downloadContent
            };

            return result;
        }
    }
}