ASP.NET Cookies简单应用 记住用户名和密码

不要试图给Password类型的TextBox赋值!

在asp.net中,不要试图给Password类型的TextBox控件赋值! 无论是在设计或是运行时,都不可以的。

猜测的原因是,password类型的TextBox控件从根本上,没有Text属性的Set方法,只有Get !!


同样,html中的Input控件,如果设置为ruanat="server",password类型的Input控件也是一样。无论是在设计或是运行时,都不容许设置它的值。

解决办法:txtPassword.Attributes["value"] = "123";

前言

          一般只要有会员、用户机制的网站或论坛在登录的时候都会有这么一个复选框——[记住我的名字 | 两周内不再登陆 | ],说法较多,实现起来差不多,本文做了一个简单的例子并附带了一个C# Cookies帮助类 CookiesHelper.cs和实现代码片段,希望能对初学者有帮助: )

推荐文章

          1.     林信良 index.dat文件剖析  较深入分析cookies在index.dat中存入情况

          2.     MSDN —— ASP.NET Cookie 概述 很全面很详细的介绍了Cookies

正文

          CookiesHelper.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace TLibrary.ObjectHelper
{
    
public class CookiesHelper
    {

        
#region 获取Cookie

        
/// <summary>
        
/// 获得Cookie的值
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <returns></returns>
        public static string GetCookieValue(string cookieName)
        {
            
return GetCookieValue(cookieName, null);
        }

        
/// <summary>
        
/// 获得Cookie的值
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <param name="key"></param>
        
/// <returns></returns>
        public static string GetCookieValue(string cookieName,string key)
        {
            HttpRequest request 
= HttpContext.Current.Request;
            
if (request != null)
                
return GetCookieValue(request.Cookies[cookieName], key);
            
return "";
        }

        
/// <summary>
        
/// 获得Cookie的子键值
        
/// </summary>
        
/// <param name="cookie"></param>
        
/// <param name="key"></param>
        
/// <returns></returns>
        public static string GetCookieValue(HttpCookie cookie, string key)
        {
            
if (cookie != null)
            {
                
if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
                    
return cookie.Values[key];
                
else
                    
return cookie.Value;
            }
            
return "";
        }

        
/// <summary>
        
/// 获得Cookie
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <returns></returns>
        public static HttpCookie GetCookie(string cookieName)
        {
            HttpRequest request 
= HttpContext.Current.Request;
            
if (request != null)
                
return request.Cookies[cookieName];
            
return null;
        }

        
#endregion

        
#region 删除Cookie

        
/// <summary>
        
/// 删除Cookie
        
/// </summary>
        
/// <param name="cookieName"></param>
        public static void RemoveCookie(string cookieName)
        {
            RemoveCookie(cookieName,
null);
        }

        
/// <summary>
        
/// 删除Cookie的子键
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <param name="key"></param>
        public static void RemoveCookie(string cookieName,string key)
        {
            HttpResponse response 
= HttpContext.Current.Response;
            
if (response != null)
            {
                HttpCookie cookie 
= response.Cookies[cookieName];
                
if (cookie != null)
                {
                    
if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
                        cookie.Values.Remove(key);
                    
else
                        response.Cookies.Remove(cookieName);
                }
            }
        }

        
#endregion

        
#region 设置/修改Cookie

        
/// <summary>
        
/// 设置Cookie子键的值
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        public static void SetCookie(string cookieName, string key, string value)
        {
            SetCookie(cookieName, key, value, 
null);
        }

        
/// <summary>
        
/// 设置Cookie值
        
/// </summary>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        public static void SetCookie(string key, string value)
        {
            SetCookie(key, 
null, value, null);
        }

        
/// <summary>
        
/// 设置Cookie值和过期时间
        
/// </summary>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        
/// <param name="expires"></param>
        public static void SetCookie(string key, string value, DateTime expires)
        {
            SetCookie(key, 
null, value, expires);
        }

        
/// <summary>
        
/// 设置Cookie过期时间
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <param name="expires"></param>
        public static void SetCookie(string cookieName, DateTime expires)
        {
            SetCookie(cookieName, 
nullnull, expires);
        }

        
/// <summary>
        
/// 设置Cookie
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        
/// <param name="expires"></param>
        public static void SetCookie(string cookieName, string key, string value, DateTime? expires)
        {
            HttpResponse response 
= HttpContext.Current.Response;
            
if (response != null)
            {
                HttpCookie cookie 
= response.Cookies[cookieName];
                
if (cookie != null)
                {
                    
if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
                        cookie.Values.Set(key, value);
                    
else
                        
if (!string.IsNullOrEmpty(value))
                            cookie.Value 
= value;
                    
if (expires != null)
                        cookie.Expires 
= expires.Value;
                    response.SetCookie(cookie);
                }
            }
            
        }

        
#endregion

        
#region 添加Cookie

        
/// <summary>
        
/// 添加Cookie
        
/// </summary>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        public static void AddCookie(string key, string value)
        {
            AddCookie(
new HttpCookie(key, value));
        }

        
/// <summary>
        
/// 添加Cookie
        
/// </summary>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        
/// <param name="expires"></param>
        public static void AddCookie(string key, string value, DateTime expires)
        {
            HttpCookie cookie 
= new HttpCookie(key, value);
            cookie.Expires 
= expires;
            AddCookie(cookie);
        }

        
/// <summary>
        
/// 添加为Cookie.Values集合
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        public static void AddCookie(string cookieName,string key, string value)
        {
            HttpCookie cookie 
= new HttpCookie(cookieName);
            cookie.Values.Add(key, value);
            AddCookie(cookie);
        }

        
/// <summary>
        
/// 添加为Cookie集合
        
/// </summary>
        
/// <param name="cookieName">Cookie名称</param>
        
/// <param name="expires">过期时间</param>
        public static void AddCookie(string cookieName, DateTime expires)
        {
            HttpCookie cookie 
= new HttpCookie(cookieName);
            cookie.Expires 
= expires;
            AddCookie(cookie);
        }

        
/// <summary>
        
/// 添加为Cookie.Values集合
        
/// </summary>
        
/// <param name="cookieName"></param>
        
/// <param name="key"></param>
        
/// <param name="value"></param>
        
/// <param name="expires"></param>
        public static void AddCookie(string cookieName, string key, string value, DateTime expires)
        {
            HttpCookie cookie 
= new HttpCookie(cookieName);
            cookie.Expires 
= expires;
            cookie.Values.Add(key, value);
            AddCookie(cookie);
        }

        
/// <summary>
        
/// 添加Cookie
        
/// </summary>
        
/// <param name="cookie"></param>
        public static void AddCookie(HttpCookie cookie)
        {
            HttpResponse response 
= HttpContext.Current.Response;
            
if (response != null)
            {
                
//指定客户端脚本是否可以访问[默认为false]
                cookie.HttpOnly = true;         
                
//指定统一的Path,比便能通存通取
                cookie.Path = "/";
                
//设置跨域,这样在其它二级域名下就都可以访问到了
                
//cookie.Domain = "chinesecoo.com";
                response.AppendCookie(cookie);
            }
        }

        
#endregion
    }
}

代码注意事项:

          1.     Cookies添加的时候注意一个Cookie可以添加多个子键

          2.     假如你不显示的设置   HttpCookie.Expires   那么此   cookie   生命期即为浏览器进程——关闭浏览器则过期

          3.     需要了解HttpCookie.Domain和HttpCookie.Path这两个属性,对于跨域和存储路径等高级应用有帮助

以下看实际调用代码

          页面加载

    protected void Page_Load(object sender, EventArgs e)
    {
        
if (!IsPostBack)
        {
            HttpCookie Cookie 
= CookiesHelper.GetCookie("UserInfo");
            
if (Cookie != null)
            {
                
this.txtUserName.Value = Cookie.Values["uName"];
            }
        }
    }

          代码说明:

                    1.     this.txtUserName是界面上输入用户名的控件,换成自己的控件名称就行;

                    2.     UserInfo为Cookie的名称,uName为Cookie的子键。

          这段代码的功能是在页面加载的时候显示用户Cookie中记录的用户名,这里也可以做成连密码一起记录然后在这里显示,这样用户就可以直接点登录按钮了

          登录验证

        string uName = this.txtUserName.Value.Trim();

        
//验证用户名密码
        if (IsLogin(uName, this.txtPass.Value.Trim()))
        {
            
//记住我的名字
            if (!string.IsNullOrEmpty(Request["remUsername"]))
            {
                HttpCookie Cookie 
= CookiesHelper.GetCookie("UserInfo");
                
if (Cookie == null)
                {
                    Cookie 
= new HttpCookie("UserInfo");
                    Cookie.Values.Add(
"uName", uName);
                    
//设置Cookie过期时间
                    Cookie.Expires = DateTime.Now.AddDays(365);
                    CookiesHelper.AddCookie(Cookie);
                }
                
else if (!Cookie.Values["uName"].Equals(uName))
                    CookiesHelper.SetCookie(
"UserInfo""uName", uName);
            }
            Response.Redirect(
"~/index.aspx");
        }

          代码说明:

补充 

               1.     根据实际的经验,一般的情况下在本地调试不设置Domain属性,挂上服务器上配上域名之后就得指定Domain参数了,否则Cookies出不来的。

                    1.     this.txtUserName和this.txtPass是界面上输入用户名和密码的控件,换成自己的控件名称就行;

                    2.     IsLogin方法是用来验证用户名和密码是否正确的,这里替换成自己的验证方法就行了。

                    3.     Request["remUsername"]是获得界面上是否选中了[记住我的名称]复选框

          这段代码的功能是在用户登录成功之后,如果选中了记住登录用户名就把用户名存入客户端的Cookie中,并设置过期时间为1年。

posted @ 2011-03-06 02:07  TiTi  阅读(954)  评论(0编辑  收藏  举报