Reputation: 1567
i got a page users downloading files from there.And when a user click download link and finish downloading file , i am insertin' a new record for my File Download Counter event. (FileID,Date,blalbla..)
But there is problem with my script ... after download starts and finish, its adding a new record but after this, its fires event again and making a new record too.So 1 download and 2 new download record. here is my script;
if (Page.Request.QueryString["FileID"] != null)
{
OleDbCommand command = new OleDbCommand("select * from Dosyalar where DosyaID=" + Page.Request.QueryString["FileID"].ToString(), veri.baglan());
string dosyaAdi = "";
int DosyaID = 0;
OleDbDataReader dr = command.ExecuteReader();
while (dr.Read())
{
dosyaAdi = Server.MapPath("formlar") + "\\" + dr["URL"].ToString();
DosyaID = Convert.ToInt32(dr["FileID"]);
}
dr.Close();
FileInfo dosya = new FileInfo(dosyaAdi);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + dosya.Name);
Response.AddHeader("Content-Length", dosya.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(dosyaAdi);
// INSERT A NEW RECORD
OleDbCommand ekle = new OleDbCommand("Insert into Indirilenler (FileID,Tarih) values (@p1,@p2)", veri.baglan());
ekle.Parameters.AddWithValue("p1", FileID);
ekle.Parameters.AddWithValue("p2", DateTime.Now.ToShortDateString());
ekle.ExecuteNonQuery();
Response.Flush();
Response.End();
Upvotes: 0
Views: 2764
Reputation: 3340
The problem is that the browser is actually making two requests to get the file. This is typical behaviour.
Either you can turn OutputCaching on this page on. This should mean that the browser's second request won't hit your server, and thus only record one entry, but you also need to make sure that you don't have the debug flag set in your web.config file.
The other option is to detect the request type. I think that the first request the browser sends is often a HEAD request and not a GET, or POST. You could detect and handle these appropriately but I think the first option maybe more reliable.
Also, you should really be coding this as a ASPX Handler not a page. This means you could avoid the response.Clear()
and thus you don't confuse the browser as to what the content type of the URI is.
Upvotes: 2