我正在尝试使用Web API 2下载文件。但是浏览器提供了#34;网页不可用"当我直接在浏览器中提供网址时。
我写了以下自定义操作
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检查方法时,它会显示正确的响应。如何强制浏览器下载文件? 感谢
答案 0 :(得分: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>