簡體   English   中英

使用Web API 2下載文件

[英]Download File using web api 2

我正在嘗試使用Web API 2下載文件。但是當我在瀏覽器中直接提供URL時,瀏覽器顯示“網頁不可用”。

我寫了以下自定義操作

 public class FileActionResult : IHttpActionResult
    {
        public FileActionResult(string data)
        {
            this.Data = data;
        }

        public string Data { get; private set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            string tempFolderPath = HttpContext.Current.Server.MapPath("~/api/tempfiles");
            HttpResponseMessage response = new HttpResponseMessage();
            Guid guid = Guid.NewGuid();
            string folderPath = Path.Combine(tempFolderPath, guid.ToString());
            if(!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string filePath = Path.Combine(folderPath, guid.ToString() + ".json");
            File.WriteAllText(filePath, Data);
            string zipFile = folderPath + ".zip";
            ZipFile.CreateFromDirectory(folderPath, zipFile);
            response.Content = new StreamContent(File.OpenRead(zipFile));
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "file.zip",
                DispositionType = "attachment"
            };
            return Task.FromResult(response);
        }
    }

我不確定這里出什么問題了。 有人可以幫我嗎?

編輯當我使用Google-PostMan檢查方法時,它顯示正確的響應。 如何強制瀏覽器下載文件? 謝謝

該代碼工作正常。 但是,此問題與Telerik Control有關。 我在網站上使用Telerik控件。 Telerik在下載文件時進行了一些壓縮。 我不得不繞過我的網址,以使其工作。

    <sectionGroup name="telerik.web.ui">
      <section name="radCompression" type="Telerik.Web.UI.RadCompressionConfigurationSection, Telerik.Web.UI" allowDefinition="MachineToApplication" requirePermission="false"/>
    </sectionGroup>
  </configSections>

  <telerik.web.ui>
    <radCompression>
      <excludeHandlers>
        <add handlerPath="some path" matchExact="false"/>
      </excludeHandlers>
    </radCompression>
  </telerik.web.ui>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM