黑马程序员_学习日记72_724ASP.NET(ViewState、Cookie、Session、登录、分页存储过程)

来源:互联网 发布:Python模拟鼠标移动 编辑:程序博客网 时间:2024/05/10 17:11
 

一、ViewState
viewstate适用于同一个页面不关闭的情况下多次与服务器交互。
禁用ViewState
enableviewstate=false;
禁用ViewState后Form版不受影响 ,因为form表单元素的值可以直接post提交;div版受影响,因为其值不能直接post,要通过隐藏域提交。

二、Cookie
Cookie是能让网站服务器端少量数据存储到客户端的硬盘或内存,并读取出来的一种技术。
(一)客户端发送请求报文时,会将Cookie附加发送到服务器端。服务器端通过Request.Cookie来获取客户端发来的Cookie信息。
protected void Page_Load(object sender, EventArgs e){    //从客户端请求中获取cookie    for (int i = 0; i < Request.Cookies.Count; i++)    {        Response.Write(Request.Cookies[i].Value);    }    //怎么往客户端写cookie    //Response.Cookies.Add();    //Cookie也是存在客户端的key-value对集合    Response.AppendCookie(new HttpCookie("laoma", "shit"));            //这时候不是将cookie生成到响应流里面的cookie都给干掉了,只是不生成响应的cookie头部    Response.Cookies.Clear();}

(二)设置cookie过期将客户端cookie删除
protected void Page_Load(object sender, EventArgs e){    int cookieCount = Request.Cookies.Count;    //从客户端请求中获取cookie    for (int i = 0; i < cookieCount; i++)    {        //创建一个新的cookie,只不过名字跟请求来的一样        HttpCookie cookie = new HttpCookie(Request.Cookies[i].Name);        //在服务器端不能直接清空浏览器端的cookie。将过期时间设为一小时前,浏览器自动清空过期的cookie        cookie.Expires = DateTime.Now.AddHours(-1);                    Response.Cookies.Add(cookie);    }}

主域的cookie能被所有的子域访问到,但子域的cookie要想让主域访问需要把Domain设置为主域名。
如果设置过期时间,则cookie存在硬盘中,如果没有设置,则cookie存在内存中。
如果想让子域的cookie让主域也能访问,则设置如下:
cookie.Secure =false;

三、Session
提供了一种把信息保存在服务器内存中的一种方式,它能存储任何数据类型包括自定义对象。

四、登录
 
(一)
/// <summary>/// 登录过程:/// 1、第一次get,将cookie中的userName信息拿出来放在txtUserName中/// 2、PostBack后,将Session中的验证码与输入的验证码进行比较/// 3、登录成功,将用户名写到cookie中,将用户信息放到session中/// 4、登录失败,清空密码,显示登录失败/// </summary>public partial class Login : System.Web.UI.Page{    public PersonBll personBll=new PersonBll();//不要把new PersonBll()丢了    public string JsScriptData;    protected void Page_Load(object sender, EventArgs e)    {        if (IsPostBack)        {            //Session["validateCode"]需要ToString()转化为字符串格式才能进行比较            if (Session["validateCode"].ToString() != txtCode.Text)            {                this.RegisterStartupScript("valiCode","<script>alert('验证码错误!')</script>");                return;            }            ParameterForLogin parameterForLogin = new ParameterForLogin();            parameterForLogin.Name = txtUserName.Text.Trim();            parameterForLogin.Pwd = txtPwd.Text;            PersonModel person = personBll.IsUserOk(parameterForLogin);            //登陆成功            if (person != null)            {                //把用户名写到cookie里面去                HttpCookie cookie = new HttpCookie("user", this.txtUserName.Text);                cookie.Expires = DateTime.Now.AddDays(7);                Response.AppendCookie(cookie);                //登录成功后把用户信息放到session里面去                Session["UserInfo"] = person;                Response.Redirect("ShowPageDataBuilding.aspx");            }            else            {                //文本框赋值操作是在InitComplete事件完了之后,执行processPostData()                //在此方法中将表单提交过来的值放到文本框中去                txtPwd.Text = string.Empty;                //Response.Write("<script>alert('登录失败!')</script>");                //Response.End();                JsScriptData = "alert('登录失败!')";                return;            }        }        //第一次请求        else        {            this.txtUserName.Text = Request.Cookies["user"] == null ? string.Empty : Request.Cookies["user"].Value;        }    }}

(二)验证码放到Session中
public class ValidateCodeHandler : IHttpHandler,IRequiresSessionState {        public void ProcessRequest (HttpContext context) {        context.Response.ContentType = "image/jpeg";                ValidateCode validateCode = new ValidateCode();        string strValidateCode = validateCode.CreateValidateCode(4);                //把验证码放到Session中,进行后续的判断处理        context.Session["validateCode"] = strValidateCode;                validateCode.CreateValidateGraphic(strValidateCode, context);        context.Response.Write(validateCode);    }     public bool IsReusable {        get {            return false;        }    }}

(三)所有的WinForm、WebForm都要有自己的基类,将Session中的信息放到基类属性中,在基类中判断用户Session是否过期
public class MyBasePage:System.Web.UI.Page{    public PersonModel Person { get; set; }    public virtual void Page_Load(object sender, EventArgs e)    {        Person = (PersonModel)Session["UserInfo"];        if (Person == null)        {            this.Response.Redirect("~/Login.aspx");        }    }}

五、分页存储过程
create proc GetPageDataBuilding@pageSize int,@pageIndex int,@totalCount int outputasselect * into #Temp from --根据中间查询结果创建了一个临时表(select B.*,P.ProjectName,U.UName,Br.BranchName from BuildingInfo as Bleft join ProjectInfo as P on P.Id=B.ProjectIdleft join UserInfo as U on U.Id=P.SubByleft join Branch as Br on P.BranchId=Br.Id) as Tdeclare @str nvarchar(1000);set @str=('select top('+CAST(@pageSize as nvarchar(32))+') * from #Temp where Id not in(select top('+case((@pageIndex-1)*@pageSize as nvarchar(32))+') Id from #Temp order by Id)order by Id')exec (@str)print @strselect @totalCount=COUNT(1) from #Temp

小知识
断点空心表示程序集与设的断点不一致。
response在Redirect之前有write,输出时write的内容不会丢失。
原创粉丝点击