首页  ·  知识 ·  云计算
asp.net(C#)海量数据表高效率分页算法(不使用存储过程)
佚名  http://www.51iter.com  综合  编辑:dezai  图片来源:网络
目的: 对输入的字串长度,范围,格式和类型进行约束. 在开发ASP.NET程序时使用请求验证防止注入攻击. 使用ASP.NET验证控件进行输入验证.

目的:

对输入的字串长度,范围,格式和类型进行约束.
在开发ASP.NET程序时使用请求验证防止注入攻击.
使用ASP.NET验证控件进行输入验证.
对不安全的输出编码.
使用命令参数集模式防止注入攻击.
防止错误的详细信息被返回到客户端.

  概述 :

  你应该在程序中验证所有的不信任输入.你应该假定所有的用户输入都是非法的.用户可以在应用程序中提供表单字段,查询字串,客户端cookies和浏览器环境值比如用户代理字串和IP地址等.

  弱输入校验通常为注入攻击提供了机会.下面是常见的利用弱输入校验或无输入校验进行攻击的手段.

SQL 注入(SQL injection). 如果你使用用户的输入值来动态构造SQL语句,那么数据库可能执行攻击性的有害SQL语句.

跨站脚本(Cross-site scripting). 跨站脚本攻击利用网页验证漏洞注入客户端脚本.接下来这些代码被发送到受信任的客户端电脑上并被浏览器解释执行.因为这些代码来自受信任的站点,所以浏览器无法得知这些代码是有害的.

未授权的文件访问(Unauthorized file access).如果你的代码从调用者那里接受输入,恶意用户可以看到你对文件的操作过程从而访问那些受保护的文件或者使用你的代码注入非法数据.

  注意 : 注入攻击可通过使用HTTP或HTTPS Secure Socket Layer(SSL) 连接. 传输加密技术不能用来防御攻击.

  通常的输入验证方法总结如下.你应在所有的需要通过网络输入的地方进行验证,比如文本框和其它表单输入字段, 查询字串参数,cookies,服务器端变量和网络方法参数.注意,过滤策略应该是只允许正确的输入然后拒绝非法输入.这是因为定义正确的输入策略比过滤所有的非法输入要容易,那通常很难包括所有的非法输入.

  通入如下几个方面验证输入内容:

约束.验证是否输入的是正确的类型,字符长度,格式和范围.可以应用ASP.NET验证控件来约束服务器控件输入.约束其它来源的输入可以使用正则表达式和自定义的验证规则.

拒绝.检测已知的有害数据输入并拒绝.

过滤.有时候你会希望过滤掉用户输入中那些有安全隐患的那些部分.例如,你的程序允许自由格式的输入,比如备注字段,你会允许特定的安全HTML标记象<b>,<i>及其它的HTML标记.

  步骤提要

  通过以下步骤保护你的ASP.NET程序不受注入式攻击危害 :

第一步.使用ASP.NET请求验证.
第二步.约束输入.
第三步.对不安全的输出进行编码.
第四步.对SQL查询语句使用命令参数.
第五步.验证ASP.NET的出错信息没有泄漏至客户端.

  下面的章节将对这些步骤进行详细讨论.

  第一步.使用ASP.NET请求验证.

  默认地,ASP.NET 1.1和2.0请求验证会对送至服务器的数据检测是否含有HTML标记元素和保留字符.这可以防止用户向程序中输入脚本.请求验证会对照一个有潜在威胁的字符串列表进行匹配,如果发现异常它会抛出一个HttpRequestValidationException类型的异常.

  你可以在你的web.config文件中的<pages>元素中加入validateRequest="false" 或在单独的页面的@Pages元素里面设置ValidateRequest = "false"来禁用此项功能.

首先创建一张表(要求ID自动编号):
create table redheadedfile(
id int identity(1,1),
filenames nvarchar(20),
senduser nvarchar(20),
primary key(id)
)
然后我们写入50万条记录:
declare @i int
set @i=1
while @i<=500000
begin
    insert into redheadedfile(filenames,senduser) values('我的分页算法','陆俊铭')
    set @i=@i+1
end
GO
用Microsoft Visual Studio .NET 2003创建一张WebForm网页(本人起名webform8.aspx)
前台代码片段如下(webform8.aspx):
<%@ Page language="c#" Codebehind="WebForm8.aspx.cs" AutoEventWireup="false" Inherits="WebApplication6.WebForm8" %>


 
  WebForm8
 
 
 
  http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 
 
 
       CellPadding="0" Runat="server">
   
    


     
      
      
      
     
    

align="center"><%#DataBinder.Eval(Container.DataItem,"filenames")%>

<%#DataBinder.Eval(Container.DataItem,"senduser")%>

align="center"><%#DataBinder.Eval(Container.DataItem,"id")%>


   
  
  
页/共

记录
   

CommandName="0">首页    

上一页    

CommandName="next">下一页    

CommandName="last">尾页    当前第

ForeColor="#ff0000">页    跳页

MaxLength="5" AutoPostBack="True">


 
 

后台代码片段如下(webform8.aspx.cs)
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;

namespace WebApplication6
{
 ///


 /// WebForm8 的摘要说明。
 ///

 public class WebForm8 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.LinkButton Fistpage;
  protected System.Web.UI.WebControls.LinkButton Prevpage;
  protected System.Web.UI.WebControls.LinkButton Nextpage;
  protected System.Web.UI.WebControls.LinkButton Lastpage;
  protected System.Web.UI.WebControls.DataList datalist1;
  protected System.Web.UI.WebControls.DropDownList mydroplist;
  protected System.Web.UI.WebControls.Label LPageCount;
  protected System.Web.UI.WebControls.Label LRecordCount;
  protected System.Web.UI.WebControls.Label LCurrentPage;
  protected System.Web.UI.WebControls.TextBox gotoPage;
  const int PageSize=20;//定义每页显示记录
  int PageCount,RecCount,CurrentPage,Pages,JumpPage;//定义几个保存分页参数变量
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!IsPostBack)
   {
    RecCount = Calc();//通过Calc()函数获取总记录数
    PageCount = RecCount/PageSize + OverPage();//计算总页数(加上OverPage()函数防止有余数造成显示

数据不完整)

    ViewState["PageCounts"] = RecCount/PageSize -

ModPage();//保存总页参数到ViewState(减去ModPage()函数防止SQL语句执行时溢出查询范围,可以用存储过程分页算法来理解这句)
    ViewState["PageIndex"] = 0;//保存一个为0的页面索引值到ViewState
    ViewState["JumpPages"] = PageCount;//保存PageCount到ViewState,跳页时判断用户输入数是否超出页

码范围
    //显示LPageCount、LRecordCount的状态
    LPageCount.Text = PageCount.ToString();
    LRecordCount.Text = RecCount.ToString();
    //判断跳页文本框失效
    if(RecCount <= 20)
     gotoPage.Enabled = false;
    TDataBind();//调用数据绑定函数TDataBind()进行数据绑定运算
   }
  }
        //计算余页
  public int OverPage()
  {
   int pages = 0;
   if(RecCount%PageSize != 0)
    pages = 1;
   else
    pages = 0;
   return pages;
  }
        //计算余页,防止SQL语句执行时溢出查询范围
  public int ModPage()
  {
   int pages = 0;
   if(RecCount%PageSize == 0 && RecCount != 0)
    pages = 1;
   else
    pages = 0;
   return pages;
  }
        /*
   *计算总记录的静态函数
   *本人在这里使用静态函数的理由是:如果引用的是静态数据或静态函数,连接器会优化生成代码,去掉动态重定位项(对

海量数据表分页效果更明显)。
   *希望大家给予意见、如有不正确的地方望指正。
  */
  public static int Calc()
  {
   int RecordCount = 0;
   SqlCommand MyCmd = new SqlCommand("select count(*) as co from redheadedfile",MyCon());
   SqlDataReader dr = MyCmd.ExecuteReader();
   if(dr.Read())
    RecordCount = Int32.Parse(dr["co"].ToString());
   MyCmd.Connection.Close();
   return RecordCount;
  }
        //数据库连接语句(从Web.Config中获取)
  public static SqlConnection MyCon()
  {
   SqlConnection MyConnection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
   MyConnection.Open();
   return MyConnection;
  }
        //对四个按钮(首页、上一页、下一页、尾页)返回的CommandName值进行操作
  private void Page_onClick(object sender, CommandEventArgs e)
  {
   CurrentPage = (int)ViewState["PageIndex"];//从ViewState中读取页码值保存到CurrentPage变量中进行参数运算
            Pages = (int)ViewState["PageCounts"];//从ViewState中读取总页参数运算

   string cmd = e.CommandName;
   switch(cmd)//筛选CommandName
   {
    case "next":
     CurrentPage++;
     break;
    case "prev":
     CurrentPage--;
     break;
    case "last":
     CurrentPage = Pages;
     break;
    default:
     CurrentPage = 0;
     break;
   }
   ViewState["PageIndex"] = CurrentPage;//将运算后的CurrentPage变量再次保存至ViewState
   TDataBind();//调用数据绑定函数TDataBind()
  }

  private void TDataBind()
  {
   CurrentPage = (int)ViewState["PageIndex"];//从ViewState中读取页码值保存到CurrentPage变量中进行按钮失

效运算
   Pages = (int)ViewState["PageCounts"];//从ViewState中读取总页参数进行按钮失效运算
   //判断四个按钮(首页、上一页、下一页、尾页)状态
   if (CurrentPage + 1 > 1)
   {
    Fistpage.Enabled = true;
    Prevpage.Enabled = true;
   }
   else
   {
    Fistpage.Enabled = false;
    Prevpage.Enabled = false;
   }
   if (CurrentPage == Pages)
   {
    Nextpage.Enabled = false;
    Lastpage.Enabled = false;
   }
   else
   {
    Nextpage.Enabled = true;
    Lastpage.Enabled = true;
   }
            //数据绑定到DataList控件
   DataSet ds = new DataSet();
   //核心SQL语句,进行查询运算(决定了分页的效率:))
   SqlDataAdapter MyAdapter = new SqlDataAdapter("Select Top "+PageSize+" * from redheadedfile where id
not in(select top "+PageSize*CurrentPage+" id from redheadedfile order by id asc) order by id asc",MyCon());
   MyAdapter.Fill(ds,"news");
   datalist1.DataSource = ds.Tables["news"].DefaultView;
   datalist1.DataBind();
   //显示Label控件LCurrentPaget和文本框控件gotoPage状态
   LCurrentPage.Text = (CurrentPage+1).ToString();
   gotoPage.Text = (CurrentPage+1).ToString();
   //释放SqlDataAdapter
   MyAdapter.Dispose();
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
 
  ///


  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///

  private void InitializeComponent()
  {   
   this.Fistpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_onClick);
   this.Prevpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_onClick);
   this.Nextpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_onClick);
   this.Lastpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_onClick);
   this.gotoPage.TextChanged += new System.EventHandler(this.gotoPage_TextChanged);
   this.Load += new System.EventHandler(this.Page_Load);
}
  #endregion
        //跳页代码
  private void gotoPage_TextChanged(object sender, System.EventArgs e)
  {
   try
   {
    JumpPage = (int)ViewState["JumpPages"];//从ViewState中读取可用页数值保存到JumpPage变量中
    //判断用户输入值是否超过可用页数范围值
    if(Int32.Parse(gotoPage.Text) > JumpPage || Int32.Parse(gotoPage.Text) <= 0)
    

Response.Write("");
    else
    {
     int InputPage = Int32.Parse(gotoPage.Text.ToString()) - 1;//转换用户输入值保存在int型

InputPage变量中
     ViewState["PageIndex"] = InputPage;//写入InputPage值到ViewState["PageIndex"]中
     TDataBind();//调用数据绑定函数TDataBind()再次进行数据绑定运算
    }
   }
      //捕获由用户输入不正确数据类型时造成的异常
   catch(Exception exp)
   {
    Response.Write("");
   }
  }
 }
}

 


 

本文作者:佚名 来源:http://www.51iter.com
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读