注册,登入
今天记录的一个小模块是注册和登入。 源码地址:https://github.com/SeaLee02/FunctionModule RegistLoginFunction文件夹下就是源码。
我们先来谈谈注册,现在注册基本需要手机号码,一般会把手机号码当做你的登入名,利用短信验证码来实现实名制。
那我只是简单的模拟了下注册,其中需要填写的就是用户名,密码,和手机号(做验证)。
来看看注册页面:
这里手机号获取短信的部分
我们的前台逻辑
function Confirm() { var LoginName = $("#LoginName").val(); if (LoginName === "" || LoginName === null) { alert("请填写用户名!"); $("#LoginName").focus(); return false; } var Loginpassword = $("#Loginpassword").val(); if (Loginpassword === "" || Loginpassword === null) { alert("请填写密码!"); $("#Loginpassword").focus(); return false; } var RPassWord = $("#RPassWord").val(); if (RPassWord === "" || RPassWord === null) { alert("请填写确认密码!"); $("#RPassWord").focus(); return false; } if (RPassWord !== Loginpassword) { alert("两次密码不一样!"); $("#RPassWord").focus(); return false; } var Tel = $("#Tel").val(); var verify_tel = /^1[34578]\d{9}$/; if (!verify_tel.test(Tel)) { alert("请填写正确的手机号码!"); $("#Tel").focus(); return false; } var code = $("#code").val(); if (code === "" || code === null) { alert("请填写验证码!"); $("#code").focus(); return false; } if (code!=$("#hfCode").val()) { alert("您输入的验证码跟系统的不匹配"); $("#code").focus(); return false; } } var result = true; function GetCode() { var Tel = $("#Tel").val(); var verify_tel = /^1[34578]\d{9}$/; if (!verify_tel.test(Tel)) { result = false; alert("请填写正确的手机号码!"); $("#Tel").focus(); return false; } result = true;
//这个ajax来去访问我们的接口,来发送短信 $.ajax({ type: "post", url: "RegisterHandler.ashx", datatype: "json", data: "type=GetCode&Phone="+Tel, async: false, //改为同步 success: function (data) { console.log(data); var GetData = data.toString().split('-')[0]; //alert(GetData); console.log(GetData); if (GetData == 0) { alert("该号码已注册!"); } else if (GetData == 1) { $("#hfCode").val(data.toString().split('-')[1]); alert("发送成功!"); } else if (GetData == 2) { alert("发送失败,请重新获取!"); } } }) } //计时器 var bb; $("#GCode").bind("click", function () { GetCode(); if (!result) { return result; } $(this).attr("disabled", "disabled"); $(this).attr("data-flag", "60"); Test(); bb = setInterval("Test()", 1000); }); function Test() { $("#GCode").css("background-color", "#808080"); var BeginValue = $("#GCode").attr("data-base"); var BeginFlag = $("#GCode").attr("data-flag"); $("#GCode").val(BeginValue + $("#GCode").attr("data-flag")); BeginFlag = Number(BeginFlag) - 1; if (BeginFlag == 0) { BeginFlag = ""; } $("#GCode").attr("data-flag", BeginFlag); if (BeginFlag == "-1") { $("#GCode").removeAttr("disabled"); $("#GCode").css("background-color", "#fff"); clearInterval(bb); } } </script>
后台代码
protected void btnRegister_Click(object sender, EventArgs e) { FunctionDemo.BLL.Users userBll = new FunctionDemo.BLL.Users(); //利用可选参数来赋值 if (userBll.Exists(LoginName:LoginName.Value)) { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('次用户名已存在');", true); return; } FunctionDemo.Model.Users userModel = new FunctionDemo.Model.Users(); userModel.LoginName = LoginName.Value; userModel.PassWord = Loginpassword.Value; if (userBll.Add(userModel)>0) { Response.Redirect("../Login/LoginDemo.aspx"); } else { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('注册出现问题');", true); return; } }
最后来看看我们如何获取短信
我们需要的命名空间
核心代码:
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; JavaScriptSerializer java = new JavaScriptSerializer(); string type = context.Request.Form["type"] == null ? "" : context.Request.Form["type"].ToString(); if (type == "GetCode") { string Phone = context.Request.Form["Phone"] == null ? "" : context.Request.Form["Phone"].ToString(); Random ran = new Random(); string strNumber = ran.Next(1000, 9999).ToString(); //你的验证码 string a = Send(Phone, strNumber, context); // s格式:sms&stat=100&message=发送成功 string[] strsplit = a.Split('&'); string[] s = strsplit[strsplit.Length - 2].Split('='); int num = Convert.ToInt32(s[s.Length - 1]); if (num == 100) { context.Response.Write(java.Serialize(1 + "-" + strNumber).Trim('"'));//发送成功 } else { context.Response.Write(java.Serialize(2 + "-" + 000).Trim('"'));//发送失败 } } context.Response.Write(java.Serialize(""));//发送失败 } /// <summary> /// 发送信息 这个方法官网里面模板,自己自己去下载 /// </summary> /// <param name="iPhone">电话号码</param> /// <param name="Num">随机数</param> /// <param name="context"></param> /// <returns></returns> private string Send(string iPhone, string Num, HttpContext context) { //官网-->www.sms.cn string sendurl = "http://api.sms.cn/sms/"; //这个文本格式需要自己在平台里面设置模板,格式必须为一样的 string content = "您的验证码为:"+Num+", 5分钟有效。【SeaLee】"; string mobile = iPhone; StringBuilder sbTemp = new StringBuilder();
//uid和pwd可以去网站注册得到,仔细阅读文档,这个获取短信的方法也要源码 string uid = ""; //ConfigurationManager.AppSettings["uid"].ToString(); string pwd = "";// ConfigurationManager.AppSettings["pwd"].ToString(); string Pass = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd + uid, "MD5"); //应要求传的pwd必须是uid和pwd利用md5加密 // 全文变量 sbTemp.Append("ac=send&uid=" + uid + "&pwd=" + Pass + "&mobile=" + mobile + "&content=" + content + "&format=txt"); //json格式变量 {"code":"value"} //sbTemp.Append("ac=send&uid=" + uid + "&pwd=" + Pass + "&template=402086&mobile=" + mobile + "&content={\"code\":\""+Num+"\"}&format=txt"); byte[] bTemp = Encoding.GetEncoding("GBK").GetBytes(sbTemp.ToString()); //我们传递的参数编个码,不然出现中发给别人的就是乱码 string postReturn = doPostRequest(sendurl, bTemp); //利用httprequest去访问网址来获取消息 return postReturn; } /// <summary> ///访问url把参数传过去,给注册者发信息 /// </summary> /// <param name="url"></param> /// <param name="bData"></param> /// <returns></returns> private static String doPostRequest(string url, byte[] bData) { HttpWebRequest hwRequest; HttpWebResponse hwResponse; string result = string.Empty; try { hwRequest = (HttpWebRequest)WebRequest.Create(url); hwRequest.Timeout = 5000;//有效时间为5分钟 hwRequest.Method = "POST"; hwRequest.ContentType = "application/x-www-form-urlencoded"; hwRequest.ContentLength = bData.Length; Stream strem = hwRequest.GetRequestStream(); strem.Write(bData, 0, bData.Length); //把我们的参数以流的形式写人 strem.Close(); } catch (Exception mess) { return result; } try { hwResponse = (HttpWebResponse)hwRequest.GetResponse(); StreamReader sr = new StreamReader(hwResponse.GetResponseStream(), Encoding.ASCII); //获取返回来的流 result = sr.ReadToEnd(); // sr.Close(); hwResponse.Close(); } catch (Exception err) { return result; } return result; }
有没有觉得我们的 doPostRequest 方法 很熟悉,之前的 HttpWebRequest类之基本定义 这边文章简单的介绍下HttpWebRequest类的两种访问url方式,
获取短信用的就是post提交方式,很多的接口都会使用这种用法,很常见的。
我们的注册就介绍到这。
在来看看我们的登入
登入最常见的问题的就是需要保存信息,需要知道是谁登入了这个网站,我们好取这个人的信息。那么就需要涉及到页面保存信息的方法了。
我用的是Session存数据,这样会有一个问题,时间过长,我的Session值就会消失了,这里还用到了Cookie。
简单的前台:
脚本:
//点击图片获取新的验证码 $("img").click(function () { var dd = $(this).attr("src"); //访问一次verify_code就会得到一个随机数 如果不设置src点击图片并不会去访问这个处理程序,就随便加一个参数就可以 $(this).attr("src", dd + "?time=" + +Math.random()); })
后台代码:
/// <summary> /// 登入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void bt_Login_Click(object sender, EventArgs e) { BLL.Users usersBLL = new BLL.Users(); String name = LoginName.Value.Trim(); string pwd = Loginpassword.Value.Trim(); string codes = code.Value.Trim(); if (string.IsNullOrEmpty(name)) { //两种弹框 //Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script>alert('请输入登录名');</script>"); ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('请输入登录名');", true); return; } if (string.IsNullOrEmpty(pwd)) { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('请输入密码');", true); return; } #region 验证码 if (string.IsNullOrEmpty(codes)) { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('请输入验证码');", true); return; } if (HttpContext.Current.Session["dt_session_code"]==null) { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('验证码过期,请重新获取');", true); return; } if (codes.Trim().ToLower()!=HttpContext.Current.Session["dt_session_code"].ToString().ToLower()) { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('您输入的验证码跟系统的不一样');", true); return; } #endregion //是否存在用户名 利用命名参数 if (!usersBLL.Exists(LoginName:name)) { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('此用户名不存在');", true); return; } if (!usersBLL.Exists(LoginName:name,PassWord:pwd)) { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('登入名或密码不正确');", true); return; } //Session存一遍 Model.Users userModel = usersBLL.GetModel(name,pwd); Session["UserModel"] = userModel; Session.Timeout = 1; //再用cookies写一遍 解决时间超时问题 Utils.WriteCookie("UserName", "FunctionDemo", userModel.LoginName); Utils.WriteCookie("UserPwd","FunctionDemo",userModel.PassWord); Model.LoginLog logModel = new Model.LoginLog(); logModel.UserID = userModel.ID; logModel.LoginTime = DateTime.Now; logModel.Remark = IPAddress; //登入IP if (new BLL.LoginLog().Add(logModel)>0) { Response.Redirect("TestDemo1.aspx"); } else { ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "alert('登入日志出问题了');", true); return; } }
cookie的存取
/// <summary> /// 写cookie值 /// </summary> /// <param name="strName">名称</param> /// <param name="strValue">值</param> public static void WriteCookie(string strName, string key, string strValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; if (cookie == null) { cookie = new HttpCookie(strName); } //cookie.Value = strValue; 一般这样设置就可以了 cookie[key] = UrlEncode(strValue); //子健设置 HttpContext.Current.Response.AppendCookie(cookie); } /// <summary> /// 读cookie值 /// </summary> /// <param name="strName">名称</param> /// <returns>cookie值</returns> public static string GetCookie(string strName, string key) { if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null) return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString()); return ""; }
登没登入,我们再页面的加载时间里面去写
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //是否登入 if (PageBase.GetUseInfo() == null) { Response.Redirect("LoginDemo.aspx"); } } }
PageBase类里面的方法
public static Model.Users GetUseInfo() { if (IsLogin()) { Model.Users userModel =HttpContext.Current.Session["UserModel"] as Model.Users; if (userModel != null) { return userModel; } } return null; } public static bool IsLogin() { if (HttpContext.Current.Session["UserModel"] != null) { return true; } else { string name = Utils.GetCookie("UserName", "FunctionDemo"); string pwd = Utils.GetCookie("UserPwd", "FunctionDemo"); Model.Users userModel = new BLL.Users().GetModel(name, pwd); if (userModel != null) { HttpContext.Current.Session["UserModel"] = userModel; return true; } } return false; }
以上就是登入。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步