【问题标题】:Download File using web api 2使用 web api 2 下载文件
【发布时间】:2014-11-18 09:53:01
【问题描述】:

我正在尝试使用 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 检查方法时,它会显示正确的响应。如何强制浏览器下载文件? 谢谢

【问题讨论】:

  • 这段代码对我来说看起来不错。您的 WebAPI 方法可能有问题?你确定你在那里使用了正确的 HTTP 动词吗?
  • 我的意思是“页面不可用”可能导致错误的方法调用,即您的方法需要 GET 但您使用 POST,或者方法参数数量错误,或者自定义路由问题。尝试使用 F12 浏览器工具接听您的电话并分析输入参数和服务器响应。
  • 我要通过点击url来调试方法

标签: c# asp.net-web-api asp.net-web-api2


【解决方案1】:

代码运行良好。但是,该问题与 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>

【讨论】:

    猜你喜欢
    • 2018-01-09
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 2014-08-02
    • 2021-02-13
    • 2018-02-01
    相关资源
    最近更新 更多