如何防止两次Page_Load Running - Page.IsPostBack总是false

本文关键字:Page Running Load IsPostBack false 总是 两次 何防止 | 更新日期: 2023-09-27 18:14:23

在一个奇怪的情况下,我的page_Load运行了两次,我所有的代码都在page_Load。
我不能使用Page.IsPostBac,因为在两个Page_Loads中,它都是假的。
但什么是奇怪的情况?
在我的项目中有一个下载文件的页面,
当你点击一个下载链接(我使用锚,所以IsPostBack是假的)page_Load运行,在页面加载我检查下载路径Querystring。
如果DownloadPath不为空,它跳转到一个处理程序。通过传递DownloadPath来显示下载窗口给我的用户。
在此过程中,我的数据库中有一些日志,由于两次运行,它们将是重复的。
但是当两次运行帐目时呢?当你尝试通过互联网下载管理器下载链接时,page_Load运行两次!

我怎么能防止page_Load的第二次运行或有一种方法来识别它?

编辑:


my page_Load:

namespace NiceFileExplorer.en
{
    public partial class Download : System.Web.UI.Page
    {
        public string Folders = "";
        public string Files = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Statistics_body_inside.DataBind();
            if (Request.QueryString["Path"] != null)
            {
                if (Request.QueryString["Path"] == "..")
                {
                    ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDoThatAnyMore", "YouCanNotDoThatAnyMore();", true);
                }
                else
                {
                    MainCodes();
                }
            }
            else
            {
                MainCodes();
            }
        }
        private void MainCodes()
        {
            if (Request.QueryString["DownloadPath"] != null)
            {
                string DownloadPath = Request.QueryString["DownloadPath"].ToString();
                string FilePath = "C:" + DownloadPath.Replace(@"/", @"''");
                if (Session["User_ID"] != null)
                {
                    string FileName = Request.QueryString["FileName"].ToString();
                    string FileSize = Request.QueryString["FileSize"].ToString();
                    string FileCreationDate = Request.QueryString["FileCreationDate"].ToString();
                    int Downloaded_Count_4Today = DataLayer.Download.Count_By_UserID_Today(int.Parse(HttpContext.Current.Session["User_ID"].ToString()), DateTime.Now);
                    if (Downloaded_Count_4Today <= 10)
                    {
                        DataSet dsDownload = DataLayer.Download.Size_By_UserID_Today(int.Parse(HttpContext.Current.Session["User_ID"].ToString()), DateTime.Now);
                        if (dsDownload.Tables["Download"].Rows.Count > 0)
                        {
                            DataRow drDownload = dsDownload.Tables["Download"].Rows[0];
                            int SumOfFileSize4Today = int.Parse(drDownload["FileSizSum"].ToString());
                            if (SumOfFileSize4Today + int.Parse(FileSize) <= 1073741824)//1 GB = 1024*1024*1024 bytes = 1073741824 bytes
                            //if (SumOfFileSize4Today + int.Parse(FileSize) <= 100000)
                            {
                                //DataLayer.Download.InsertRow(
                                //           int.Parse(Session["User_ID"].ToString()),
                                //           DateTime.Now,
                                //           FilePath.Replace(@"''", @"'"),
                                //           FileName,
                                //           FileSize,
                                //           DateTime.Parse(FileCreationDate)
                                //         );
                                Response.Redirect("~/HandlerForMyFE.ashx?Downloadpath=" + HttpUtility.UrlEncode(DownloadPath));
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_SizeOverload", "YouCanNotDownloadAnyMore_SizeOverload();", true);
                            }
                        }
                        else
                        {
                            if (int.Parse(FileSize) <= 1073741824)
                            //if (int.Parse(FileSize) <= 100000)
                            {
                                //DataLayer.Download.InsertRow(
                                //           int.Parse(Session["User_ID"].ToString()),
                                //           DateTime.Now,
                                //           FilePath.Replace(@"''", @"'"),
                                //           FileName,
                                //           FileSize,
                                //           DateTime.Parse(FileCreationDate)
                                //         );
                                Response.Redirect("~/HandlerForMyFE.ashx?Downloadpath=" + HttpUtility.UrlEncode(DownloadPath));
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_SizeOverload", "YouCanNotDownloadAnyMore_SizeOverload();", true);
                            }
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_CountOverload", "YouCanNotDownloadAnyMore_CountOverload();", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "plzLoginFirst_ForDownload", "plzLoginFirst_ForDownload();", true);
                }
            }
            DirectoryInfo dir;
            string lastpath = "";
            try
            {
                lastpath = Request["path"].ToString();
            }
            catch { }
            lblTitleInHeader.Text = "Files";
            lblTitleInHeader.Text += lastpath;
            //set back
            string[] splited = lblTitleInHeader.Text.Split('/');
            lblTitleInHeader.Text = "";
            ArrayList arName = new ArrayList();
            for (int i = 0; i < splited.Length; i++)
            {
                if (splited[i] != "")
                {
                    arName.Add(splited[i]);
                }
            }
            for (int i = 0; i < arName.Count - 1; i++)
            {
                if (i != arName.Count - 1)
                {
                    lblTitleInHeader.Text += "<a href='Download.aspx?path=%2f";//%2f = /
                    for (int j = 1; j < i + 1; j++)
                    {
                        lblTitleInHeader.Text += HttpUtility.UrlEncode(arName[j].ToString() + "/");
                    }
                    lblTitleInHeader.Text += "'>" + arName[i] + "</a>" + " " + "<img class='icoSubFolder' src='../Images/Download/icoSubFolder.png' />";
                }
            }
            lblTitleInHeader.Text += arName[arName.Count - 1].ToString();
            lblTitleInHeader.Text = lblTitleInHeader.Text.Replace("/'>", "'>");
            if (lastpath != "")
            {
                //dir = new DirectoryInfo(Server.MapPath("~/Files/" + lastpath));
                dir = new DirectoryInfo(@"C:''Files''" + lastpath.Replace(@"/", @"''"));
            }
            else
            {
                //dir = new DirectoryInfo(Server.MapPath("~/Files/"));
                dir = new DirectoryInfo(@"C:''Files''");
            }
            int count4Folders = 0;
            foreach (DirectoryInfo d in dir.GetDirectories())
            {
                count4Folders++;
                DirectoryInfo dirSub = new DirectoryInfo(d.FullName);
                int iDir = 0;
                int iFile = 0;
                foreach (DirectoryInfo subd in dirSub.GetDirectories())
                {
                    iDir++;
                }
                foreach (FileInfo f in dirSub.GetFiles("*.*"))
                {
                    iFile++;
                }
                Folders += "<div class='divFoldersBody_Row'>";
                Folders += "<div class='divFoldersBody_Left'>";
                Folders += "&nbsp;";
                Folders += "</div>";
                Folders += "<div class='divFoldersBody_Name'>";
                Folders += "<span class='imgFolderContainer'><img class='imgFolder' src='../Images/Download/folder.png' /></span>";
                Folders += "<span class='FolderName'><a class='FolderLink' href='Download.aspx?path=" + HttpUtility.UrlEncode(lastpath + "/" + d.Name) + "'>";
                Folders += d.Name;
                Folders += "</a></span>";
                Folders += "</div>";
                Folders += "<div class='divFoldersBody_Count'>";
                Folders += iDir.ToString() + " Folders & " + iFile.ToString() + " Files";
                Folders += "</div>";
                Folders += "<div class='divFoldersBody_Right'>";
                Folders += "&nbsp;";
                Folders += "</div>";
                Folders += "</div>";
            }
            if (count4Folders == 0)
            {
                divFoldersHeader.Style.Add("display", "none");
            }
            int count4Files = 0;
            foreach (FileInfo f in dir.GetFiles("*.*"))
            {
                count4Files++;
                Files += "<div class='divFilesBody_Row'>";
                Files += "<div class='divFilesBody_Left'>";
                Files += "&nbsp;";
                Files += "</div>";
                Files += "<div class='divFilesBody_Name'>";
                char[] Extension_ChAr = f.Extension.ToCharArray();
                string Extension_str = string.Empty;
                int lenghth = Extension_ChAr.Length;
                for (int i = 1; i < Extension_ChAr.Length; i++)
                {
                    Extension_str += Extension_ChAr[i];
                }
                if (Extension_str.ToLower() == "rar" || Extension_str.ToLower() == "zip" || Extension_str.ToLower() == "zipx" || Extension_str.ToLower() == "7z" || Extension_str.ToLower() == "cat")
                {
                    Files += "<span class='imgFileContainer'><img class='imgFile-rar' src='../Images/Download/file-rar.png' /></span>";
                }
                else if (Extension_str.ToLower() == "txt" || Extension_str.ToLower() == "doc" || Extension_str.ToLower() == "docx")
                {
                    Files += "<span class='imgFileContainer'><img class='imgFile-txt' src='../Images/Download/file-txt.png' /></span>";
                }
                else if (Extension_str.ToLower() == "pdf")
                {
                    Files += "<span class='imgFileContainer'><img class='imgFile-pdf' src='../Images/Download/file-pdf.png' /></span>";
                }
                else if (Extension_str.ToLower() == "jpg" || (Extension_str.ToLower() == "png") || (Extension_str.ToLower() == "gif") || (Extension_str.ToLower() == "bmp") || (Extension_str.ToLower() == "psd"))
                {
                    Files += "<span class='imgFileContainer'><img class='imgFile-image' src='../Images/Download/file-image.png' /></span>";
                }
                else if (Extension_str.ToLower() == "exe")
                {
                    Files += "<span class='imgFileContainer'><img class='imgFile-exe' src='../Images/Download/file-exe.png' /></span>";
                }
                else
                {
                    Files += "<span class='imgFileContainer'><img class='imgFile-unknown' src='../Images/Download/file-unknown.png' /></span>";
                }
                Files += "<span title='" + f.Name + "' class='FileName'>";
                Files += f.Name;
                Files += "</span>";
                Files += "</div>";
                Files += "<div class='divFilesBody_FileType'>";
                Files += "<span style='color:red;'>" + Extension_str.ToUpper() + "</span>" + " File";
                //Files += Path.GetExtension(f.Name) + " File";
                Files += "</div>";
                Files += "<div class='divFilesBody_FileSize'>";
                Files += ConvertBytes.ToFileSize(long.Parse(f.Length.ToString()));
                Files += "</div>";
                Files += "<div class='divFilesBody_FileCreationDate'>";
                Files += f.CreationTime;
                Files += "</div>";
                Files += "<div class='divFilesBody_FileDownload'>";
                string Downloadpath = "/Files" + lastpath + "/" + f.Name;
                string EncodedDownloadpath = HttpUtility.UrlEncode(Downloadpath);
                Files += "<a class='FileLink' href='Download.aspx?path=" + HttpUtility.UrlEncode(lastpath) + "&Downloadpath=" + EncodedDownloadpath + "&FileName=" + HttpUtility.UrlEncode(f.Name) + "&FileSize=" + HttpUtility.UrlEncode(f.Length.ToString()) + "&FileCreationDate=" + HttpUtility.UrlEncode(f.CreationTime.ToString()) + "'>";
                Files += "<img class='imgDownload' src='../Images/Download/Download.png' />";
                Files += "</a>";
                Files += "</div>";
                Files += "<div class='divFilesBody_Right'>";
                Files += "&nbsp;";
                Files += "</div>";
                Files += "</div>";
            }
            if (count4Files == 0)
            {
                divFilesHeader.Style.Add("display", "none");
            }
            if ((count4Folders == 0) && (count4Files == 0))
            {
                divFoldersHeader.Style.Add("display", "block");
                divFilesHeader.Style.Add("display", "block");
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "hash", "location.hash = '#BreadCrumbInDownload';", true);
        }
     ....

my aspx:

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link href="css/Download.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        $(function () {
            $('#Download-body *').css({ 'zIndex': 2 });
            $('#Download-body').css({ 'overflow': 'hidden', 'position': 'relative' });
            var containerWidth = $('#Download-body').innerWidth();
            var containerHeight = $('#Download-body').innerHeight();
            var bgimgurl = $('#Download-body').css('backgroundImage').replace(/url'(|')|"|'/g, "");
            var img = $('<img src="' + bgimgurl + '" width="' + containerWidth + 'px"' + ' height="' + containerHeight + 'px" />').css({ 'position': 'absolute', 'left': 0, 'top': 0, 'zIndex': 1 });
            $('#Download-body').css({ 'background': 'transparent' }).append(img);
        });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div id="Download">
        <div id="Download-header">
            <div id="DownloadTitle">
                Download
            </div>
            <asp:Image ID="imgDownload_header_left" runat="server" ImageUrl="~/Images/Download-header-left.png" />
            <asp:Image ID="imgDownload_header_right" runat="server" ImageUrl="~/Images/Download-header-right.png" />
        </div>
        <div id="Download-body">
            <div id="Download-body-inside">
                <div id="Statistics">
                    <div id="Statistics-header">
                        <div id="StatisticsTitle">
                            Statistics
                        </div>
                        <asp:Image ID="imgStatistics_header_left" runat="server" ImageUrl="~/Images/Statistics-header-left.png" />
                        <asp:Image ID="imgStatistics_header_right" runat="server" ImageUrl="~/Images/Statistics-header-right.png" />
                    </div>
                    <div id="Statistics-body">
                        <div runat="server" id="Statistics_body_inside">
                            <asp:Label ID="lblDownload_Count_By_UserID_Title" runat="server" Text="Ur Download Count :"
                                ToolTip="Your Download Count From The Begining Of Registration UpTo Now" CssClass="lblTitleInStatistics"></asp:Label>
                            <asp:Label ID="lblDownload_Count_By_UserID" runat="server" Text="<%# Download_Count_By_UserID() %>"
                                CssClass="lblCountInStatistics"></asp:Label>
                            <br />
                            <asp:Label ID="lblDownload_Count_By_UserID_Today_Title" runat="server" Text="Ur Download Count-Today :"
                                ToolTip="Your Download Count-Today" CssClass="lblTitleInStatistics"></asp:Label>
                            <asp:Label ID="lblDownload_Count_By_UserID_Today" runat="server" Text="<%# Download_Count_By_UserID_Today() %>"
                                CssClass="lblCountInStatistics"></asp:Label>
                            <br />
                            <asp:Label ID="lblDownload_Size_By_UserID_Title" runat="server" Text="Ur Download Size :"
                                ToolTip="Your Download Size From The Begining Of Registration UpTo Now" CssClass="lblTitleInStatistics"></asp:Label>
                            <asp:Label ID="lblDownload_Size_By_UserID" runat="server" Text="<%# Download_Size_By_UserID() %>"
                                CssClass="lblCountInStatistics"></asp:Label>
                            <br />
                            <asp:Label ID="lblDownload_Size_By_UserID_Today_Title" runat="server" Text="Ur Download Size-Today :"
                                ToolTip="Your Download Size-Today" CssClass="lblTitleInStatistics"></asp:Label>
                            <asp:Label ID="lblDownload_Size_By_UserID_Today" runat="server" Text="<%# Download_Size_By_UserID_Today() %>"
                                CssClass="lblCountInStatistics"></asp:Label>
                            <br />
                            <asp:Label ID="lblDownload_Size_By_UserID_Today_Remain_Title" runat="server" Text="Ur Remain Download Size-Today :"
                                ToolTip="Your Remain Download Size-Today" CssClass="lblTitleInStatistics"></asp:Label>
                            <asp:Label ID="lblDownload_Size_By_UserID_Today_Remain" runat="server" Text="<%# Download_Size_By_UserID_Today_Remain() %>"
                                CssClass="lblCountInStatistics"></asp:Label>
                        </div>
                    </div>
                </div>
                <div id="MainDivInDownload">
                    <div id="BreadCrumbInDownload">
                        <div id="imgicoHomeContainer">
                            <asp:Image ID="imgicoHome" runat="server" ImageUrl="~/Images/Download/icoHome.png" />
                        </div>
                        <div id="lblTitleInHeaderContainer">
                            <asp:Label ID="lblTitleInHeader" runat="server" Text=""></asp:Label>
                        </div>
                        <div style="clear: both;">
                        </div>
                    </div>
                    <div runat="server" id="divFolders">
                        <div runat="server" id="divFoldersHeader">
                            <div id="divFoldersHeader_Left">
                                <asp:Image ID="divFoldersHeader_imgLeft" runat="server" ImageUrl="~/Images/Download/divsHeader_Left.png" />
                            </div>
                            <div id="divFoldersHeader_Name">
                                Folders In This Folder
                            </div>
                            <div id="divFoldersHeader_Count">
                                Total Files In This Folder
                            </div>
                            <div id="divFoldersHeader_Right">
                                <asp:Image ID="divFoldersHeader_imgRight" runat="server" ImageUrl="~/Images/Download/divsHeader_Right.png" />
                            </div>
                        </div>
                        <div id="divFoldersBody">
                            <%--                <div class="divFoldersBody_Row">
                    <div class="divFoldersBody_Left">
                        &nbsp;
                    </div>
                    <div class="divFoldersBody_Name">
                        <span class="imgFolderContainer">
                            <asp:Image CssClass="imgFolder" runat="server" ImageUrl="~/Images/Download/folder.png" />
                        </span><span class="FolderName"><a class="FolderLink" href="#">Folders In This Folder</a></span>
                    </div>
                    <div class="divFoldersBody_Count">
                        Total Files In This Folder
                    </div>
                    <div class="divFoldersBody_Right">
                        &nbsp;
                    </div>
                </div>--%>
                            <%= Folders %>
                        </div>
                    </div>
                    <div runat="server" id="divFiles">
                        <div runat="server" id="divFilesHeader">
                            <div id="divFilesHeader_Left">
                                <asp:Image ID="divFilesHeader_imgLeft" runat="server" ImageUrl="~/Images/Download/divsHeader_Left.png" />
                            </div>
                            <div id="divFilesHeader_Name">
                                Files In This Folder
                            </div>
                            <div id="divFilesHeader_FileType">
                                File Type
                            </div>
                            <div id="divFilesHeader_FileSize">
                                File Size
                            </div>
                            <div id="divFilesHeader_FileCreationDate">
                                File Creation Date
                            </div>
                            <div id="divFilesHeader_FileDownload">
                            </div>
                            <div id="divFilesHeader_Right">
                                <asp:Image ID="divFilesHeader_imgRight" runat="server" ImageUrl="~/Images/Download/divsHeader_Right.png" />
                            </div>
                        </div>
                        <div id="divFilesBody">
                            <%--                <div class="divFilesBody_Row">
                    <div class="divFilesBody_Left">
                        &nbsp;
                    </div>
                    <div class="divFilesBody_Name">
                        <span class="imgFileContainer">
                            <asp:Image runat="server" ImageUrl="~/Images/Download/file.png" CssClass="imgFile" />
                        </span><span class="FileName">Files In This Folder</span>
                    </div>
                    <div class="divFilesBody_FileType">
                        File Type
                    </div>
                    <div class="divFilesBody_FileSize">
                        File Size
                    </div>
                    <div class="divFilesBody_FileCreationDate">
                        File Creation Date
                    </div>
                    <div class="divFilesBody_FileDownload">
                        <a class="FileLink" href="#">
                            <asp:Image CssClass="imgDownload" runat="server" ImageUrl="~/Images/Download.png" />
                        </a>
                    </div>
                    <div class="divFilesBody_Right">
                        &nbsp;
                    </div>
                </div>--%>
                            <%= Files %>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</asp:Content>

thanks in advance

如何防止两次Page_Load Running - Page.IsPostBack总是false

请查看在页面上呈现的html:

每当它出现

<img src=""/>

双回发可以发生,对于某些浏览器…

如果这就是问题所在,你可以为每个按钮设置一个默认的空白图像

<asp:ImageButton ImageUrl="~/Images/blank.gif"...