Reputation: 7980
I am trying to download a file using web API 2. But the browser gives "the web page is not available" when I directly give the url in the browser.
I have written following Custom Action
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);
}
}
I am not sure what is wrong here. Can somebody help me in this?
Edit When I use Google-PostMan to check the methods it shows proper response. How to force the browser to download the file? Thanks
Upvotes: 0
Views: 2260
Reputation: 7980
The code is working fine. However the issue was related to Telerik Control. I am using Telerik controls on my website. Telerik was doing some compression while file download. I had to bypass my url to make it work.
<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>
Upvotes: 1