webfrom-横贯四方-02-密码找回+缓存的使用

1:密码找回

画一个密码找回的页面

<%@ Page Title="" Language="C#" MasterPageFile="~/Master/MainMaster.Master" AutoEventWireup="true" CodeBehind="FindPwd.aspx.cs" Inherits="BookShopManager.Web.Member.FindPwd" %>

<asp:Content ID="Content1" ContentPlaceHolderID="Header" runat="server">
    <script type="text/javascript">
        $(function () {
            $("#btnFindPwd").click(function () {
                findPwd();
            });
        });
        function findPwd() {
            var userName = $("#txtName").val();
            var userMail = $("#txtMail").val();
            if (userName != "" && userMail != "") {
                $.post("/ashx/FindPwd.ashx", { "name": userName, "mail": userMail }, function (data) {
                    alert(data);
                });
            } else {
                alert("用户名和邮箱不能为空");
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <table>
        <tr>
            <td>用户名
            </td>
            <td>
                <input type="text" id="txtName" />
            </td>
        </tr>
        <tr>
            <td>邮箱
            </td>
            <td>
                <input type="text" id="txtMail" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="button" id="btnFindPwd" value="找回密码" />
            </td>
        </tr>
    </table>
</asp:Content>
FindPwd.aspx

FindPwd.aspx.cs 中没有什么,因为直接通过Ajax跳到FindPwd.ashx页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BookShopManager.Web.Ashx
{
    /// <summary>
    /// FindPwd 的摘要说明
    /// </summary>
    public class FindPwd : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string name = context.Request["name"];
            string mail = context.Request["mail"];
            BLL.Users userInfoBLL = new BLL.Users();
            Model.Users userInfo = userInfoBLL.GetModelByLoginID(name);
            if (userInfo != null)
            {
                if (mail != userInfo.Mail)
                {
                    context.Response.Write("用户邮箱不正确!");
                }
                else {
                    userInfoBLL.FindUserPwd(userInfo);
                    context.Response.Write("密码找回方式已发送到您的邮箱,请注意查收!");
                }
            }
            else
            {
                context.Response.Write("该用户名不存在");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
Ashx中的FindPwd

其中调用了FindUserPwd方法

using System;
using System.Data;
using System.Collections.Generic;
using Maticsoft.Common;
using BookShopManager.Model;
namespace BookShopManager.BLL
{
    /// <summary>
    /// Users
    /// </summary>
    public partial class Users
    {
        //private readonly BookShopManager.DAL.Users dal = new BookShopManager.DAL.Users();
        //public Users()
        //{ }
        #region  BasicMethod

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(BookShopManager.Model.Users model, out string msg)
        {

            int isSuccess = -1;
            msg = string.Empty;
            //根据"用户名"是否存在该记录

            if (dal.ExistsByUserMail(model.Mail))
            {
                msg = "该邮箱已注册!";
            }
            else
            {
                isSuccess = dal.Add(model);
            }

            return isSuccess;

        }
        /// <summary>
        /// 是否存在该记录--"用户名"
        /// </summary>
        public bool ExistsByUserName(string LoginId)
        {
            return dal.ExistsByUserName(LoginId);
        }
        /// <summary>
        /// 是否存在该记录--"邮箱"
        /// </summary>
        public bool ExistsByUserMail(string Mail)
        {
            return dal.ExistsByUserMail(Mail);
        }
        /// <summary>
        /// 判断用户是否登录成功
        /// </summary>
        /// <param name="loginId">用户名</param>
        /// <param name="loginPwd">密码</param>
        /// <param name="msg">返回信息</param>
        /// <param name="user"></param>
        public bool CheckUserInfo(string loginId, string loginPwd, out string msg, out Model.Users user)
        {
            msg = string.Empty;
            user = dal.GetModelByLoginID(loginId);
            if (user != null)
            {
                if (user.LoginPwd != loginPwd)
                {
                    msg = "密码错误! ";
                }
                else
                {
                    msg = "登录成功! ";
                    return true;
                }
            }
            else
            {
                msg = "用户名不存在! ";
            }
            return false;
        }
        public BookShopManager.Model.Users GetModelByLoginID(string loginID)
        {
            BookShopManager.Model.Users user = dal.GetModelByLoginID(loginID);
            return user;
        }
        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="userInfoBLL"></param>
        public void FindUserPwd(Model.Users userInfo)
        {
            string guid =  Guid.NewGuid().ToString();
            userInfo.CheckCode = guid;
            dal.Update(userInfo);
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host = "smtp.163.com";//使用163的SMTP服务器发送邮件
            client.UseDefaultCredentials = true;
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            client.Credentials = new System.Net.NetworkCredential("yk1817594648@163.com", "yk112358");//163的SMTP服务器需要用163邮箱的用户名和密码作认证,如果没有需要去163申请个,
            System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
            Message.From = new System.Net.Mail.MailAddress("yk1817594648@163.com");//这里需要注意,163似乎有规定发信人的邮箱地址必须是163的,而且发信人的邮箱用户名必须和上面SMTP服务器认证时的用户名相同
            //因为上面用的用户名abc作SMTP服务器认证,所以这里发信人的邮箱地址也应该写为abc@163.com
            //Message.To.Add(userInfo.Mail);//将邮件发送给QQ邮箱
            Message.To.Add("1817594648@qq.com");//将邮件发送给QQ邮箱
            Message.Subject = "密码找回";
            Message.Body = "http://localhost:3448/Member/NewPwd.aspx?userName="+userInfo.LoginId+"&CheckCode="+guid;
            Message.SubjectEncoding = System.Text.Encoding.UTF8;
            Message.BodyEncoding = System.Text.Encoding.UTF8;
            Message.Priority = System.Net.Mail.MailPriority.High;
            Message.IsBodyHtml = true;
            client.Send(Message);
        }
        #endregion  BasicMethod
    }
}
Users.cs

需要再画一个新页面NewPwd.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Master/MainMaster.Master" AutoEventWireup="true" CodeBehind="NewPwd.aspx.cs" Inherits="BookShopManager.Web.Member.NewPwd" %>

<asp:Content ID="Content1" ContentPlaceHolderID="Header" runat="server">
    <script type="text/javascript">
        $(function () {
            $("#btnSubmit").click(function () {
                modifyPwd();
            });
        });
        function modifyPwd() {
            var userName = $("#lblName").text();
            var pwd = $("#txtPwd").val();
            var confirmPwd = $("#txtConfirmPwd").val();
            var checkCode = $("#hiddenCheckCode").val();
            if (pwd != "" && pwd == confirmPwd) {
                $.post("/ashx/NewPwd.ashx", { "name": userName, "pwd": pwd, "checkCode": checkCode }, function (data) {
                    alert(data);
                    if ("密码修改成功" == data) {
                        window.location.href = "/Member/Login.aspx";
                    }
                });
            } else {
                alert("密码不能为空而且两次输入密码要一致");
            }
        }
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <table>
        <tr>
            <td>用户名
            </td>
            <td>
                <label id="lblName"><%=UserName%></label>
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <input type="password" name="txtPwd" id="txtPwd" />
                <span id="msgPwd" style="font-size: 14px; color: red">*</span>
            </td>
        </tr>
        <tr>
            <td>确认密码:</td>
            <td>
                <input type="password" name="txtConfirmPwd" id="txtConfirmPwd" />
                <span id="msgConfirmPwd" style="font-size: 14px; color: red">*</span>
            </td>
        </tr>
        <tr>
            <input type="hidden" name="hiddenCheckCode" id="hiddenCheckCode" value="<%=CheckCode%>" />
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="button" id="btnSubmit" value="确认" />
            </td>
        </tr>
    </table>
</asp:Content>
NewPwd.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BookShopManager.Web.Member
{
    public partial class NewPwd : System.Web.UI.Page
    {
        public string CheckCode { set; get; }
        public string UserName { set; get; }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                UserName = Request["userName"];
                CheckCode = Request["CheckCode"];
            }
        }
    }
}
NewPwd.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BookShopManager.Web.Ashx
{
    /// <summary>
    /// NewPwd 的摘要说明
    /// </summary>
    public class NewPwd : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string name = context.Request["name"];
            string pwd = context.Request["pwd"];
            string checkCode = context.Request["checkCode"];
            BLL.Users userInfoBLL = new BLL.Users();
            Model.Users userInfo = userInfoBLL.GetModelByLoginID(name);
            if (userInfo != null)
            {
                if (checkCode != userInfo.CheckCode)
                {
                    context.Response.Write("找回密码已过期,请重新找回!");
                }
                else
                {
                    userInfo.LoginPwd = pwd;
                    if (userInfoBLL.Update(userInfo))
                    {
                        context.Response.Write("密码修改成功");
                    } 
                }
            }
            else
            {
                context.Response.Write("该用户名不存在");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
/ashx/NewPwd.ashx

 2:缓存使用

 经常查询但不经常修改的信息可放在缓存中.例如:发件人信息(邮箱,服务器)

首先在common中创建一个CacheHelper.cs的类

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

namespace BookShopManager.Common
{
    public class CacheHelper
    {
        /// <summary>
        /// 从缓存中获取数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object Get(string key)
        {
            Cache cache = HttpRuntime.Cache;//获取cache实例
            return cache[key];
        }
        /// <summary>
        /// 向缓存中添加数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set(string key, object value)
        {
            Cache cache = HttpRuntime.Cache;//获取cache实例
            cache[key] = value;
        }
        public static void Set(string key, object value, DateTime dateTime)
        {
            Cache cache = HttpRuntime.Cache;//获取cache实例
            cache.Insert(key, value, null, dateTime, TimeSpan.Zero);
        }
        public static void Remove(string key)
        {
            Cache cache = HttpRuntime.Cache;//获取cache实例
            cache.Remove(key);
        }

    }
}
CacheHelper

BLL中

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

namespace BookShopManager.BLL
{
    public partial class Settings
    {
        /// <summary>
        /// 根据配置项名称获取配置项的值
        /// </summary>
        /// <returns></returns>
        public string GetValue(string key)
        {
            if (BookShopManager.Common.CacheHelper.Get("setting_" + key) == null)
            {
                string value = dal.GetModelByName(key).Value;
                Common.CacheHelper.Set("setting_" + key, value);
                return value;
            }
            else
            {
                Common.CacheHelper.Get("setting_" + key) ;
            }
        }
    }
}
Settings

DAL中

using Maticsoft.DBUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace BookShopManager.DAL
{
    public partial class Settings
    {
        /// <summary>
        /// 根据key值 得到一个对象实体
        /// </summary>
        public BookShopManager.Model.Settings GetModelByName(string name)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 Id,Name,Value from Settings ");
            strSql.Append(" where Name=@Name");
            SqlParameter[] parameters = {
                    new SqlParameter("@Name", SqlDbType.NVarChar,50)
            };
            parameters[0].Value = name;

            BookShopManager.Model.Settings model = new BookShopManager.Model.Settings();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

       
    }
}
Setting

然后在修改FindUserPwd方法

 public void FindUserPwd(Model.Users userInfo)
        {
            BLL.Settings bllSetting = new Settings();
            string guid =  Guid.NewGuid().ToString();
            userInfo.CheckCode = guid;
            dal.Update(userInfo);
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Host = bllSetting.GetValue("系统邮件SMTP");//使用163的SMTP服务器发送邮件
            client.UseDefaultCredentials = true;
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            client.Credentials = new System.Net.NetworkCredential(bllSetting.GetValue("系统邮件地址"), bllSetting.GetValue("系统邮件密码"));//163的SMTP服务器需要用163邮箱的用户名和密码作认证,如果没有需要去163申请个,
            System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
            Message.From = new System.Net.Mail.MailAddress(bllSetting.GetValue("系统邮件地址"));//这里需要注意,163似乎有规定发信人的邮箱地址必须是163的,而且发信人的邮箱用户名必须和上面SMTP服务器认证时的用户名相同
            //因为上面用的用户名abc作SMTP服务器认证,所以这里发信人的邮箱地址也应该写为abc@163.com
            Message.To.Add(userInfo.Mail);//将邮件发送给QQ邮箱
            //Message.To.Add("1817594648@qq.com");//将邮件发送给QQ邮箱
            Message.Subject = "密码找回";
            Message.Body = "http://localhost:3448/Member/NewPwd.aspx?userName="+userInfo.LoginId+"&CheckCode="+guid;
            Message.SubjectEncoding = System.Text.Encoding.UTF8;
            Message.BodyEncoding = System.Text.Encoding.UTF8;
            Message.Priority = System.Net.Mail.MailPriority.High;
            Message.IsBodyHtml = true;
            client.Send(Message);
        }
FindUserPwd

 

posted @ 2017-09-17 09:56  逍遥小天狼  阅读(211)  评论(0)    收藏  举报