I am trying to allow users to download a file, and have been trying for quite a while to no avail to get this to work. The code I have been using is:
Response.ClearHeaders();
Response.Clear();
Response.BufferOutput = true;
Response.AddHeader("Content-disposition",
"attachment; filename= "+ Path.GetFileName(path) + fileType);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(buffer);
Response.Flush();
Response.Close();
Response.End();
Unfortunately nothing happens when I try to make it run except for lots of exceptions:
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.NullReferenceException' occurred in WebDev.WebHost40.dll
(etc)
Changing my debugging settings I discovered that the exception I was getting was
"Server cannot set content type after HTTP headers have been sent."
I have searched through Google and attempted many solutions but nothing have worked so far. This is the only time Response has been used as far as I know - unless there is some background processes occurring (if so, how do I change this?). Please note that I am using Asp.NET MVC.
Any ideas?
Edit: Here is some context, which might help to resolve the problem:
The code is inside a Webmethod that has been called via Ajax, the reason being that I needed to call the server side via the client side (bad practice, but it was needed in the time provided) and I also needed to pass through a parameter.
Here is the ajax call:
$("#Button").each(function() {
this.submitting = false; //To prevent double-clicking problems
}).on("click", function (e) {
if (e.preventDefault) e.preventDefault();
$.ajaxSetup({ cache: false });
e.preventDefault();
if (!this.submitting)
{
this.submitting = true;
var self = this;
$.ajax({
url: 'Controller/retrieveFile',
type: 'POST',
data: { SystemNumber: $("#Button").val() },
dataType: 'json',
success: function (data) {
self.submitting = false;
},
error: function() {
self.submitting = false;
}
});
}
});
Is this, perhaps, a problem with the return value? Currently I am returning
Json(true, JsonRequestBehavior.AllowGet);