【发布时间】: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