MVC Web Api 2:如何允许并行下载文件

时间:2015-11-10 06:49:55

标签: c# asp.net-mvc-5

嗯,下面是我的代码,它涉及下载一个zip文件。一切正常,但是当有一个正在进行的下载请求时,它无法下载文件。

public class ZipController : ApiController
    {
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public HttpResponseMessage DownloadFile()
        {
            var zipPath = ConfigurationManager.AppSettings["FilePath"];
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            try
            {
                if (File.Exists(zipPath))
                {
                    var stream = new FileStream(zipPath, FileMode.Open);
                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "abc.zip"
                    };
                }
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
            }
            return result;
        }

    }

1 个答案:

答案 0 :(得分:1)

当我提供文件访问权限时,它工作正常。

public class ZipController : ApiController
    {
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        [System.Web.Http.HttpGet]
        public HttpResponseMessage DownloadFile()
        {
            var zipPath = ConfigurationManager.AppSettings["FilePath"];
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new FileStream(zipPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            try
            {
                if (File.Exists(zipPath))
                {

                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "abc.zip"

                    };

                }
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
            }
            return result;
        }
     }