webfrom-横贯四方-01

说明:数据库存放位置:https://pan.baidu.com/s/1nv4yIQt

1:通过动软生成代码

1.1 修改数据库连接方式,创建"母版页Master/MainMaster.Master",通过"母版页"创建"注册页面Member/Register.aspx"

下面主要是对注册页面进行完善.

2.1 添加验证码

将"验证码"代码放置到"Ashx"文件夹中

<%@ WebHandler Language="C#" Class="ValidateCode" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;

public class ValidateCode : IHttpHandler, IRequiresSessionState
{
    HttpContext context;
    public void ProcessRequest (HttpContext context1) {
        this.context = context1;
        CreateCheckCodeImage(GenerateCheckCode());
    }

    private string GenerateCheckCode()
    {
        int number;
        char code;
        string checkCode = String.Empty;

        System.Random random = new Random();

        for (int i = 0; i < 5; i++)
        {
            number = random.Next();

            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('0' + (char)(number % 10));
            //code = (char)('A' + (char)(number % 26));

            checkCode += code.ToString();
        }

        //Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
        context.Session.Add("vCode", checkCode);
        return checkCode;
    }

    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;

        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
        Graphics g = Graphics.FromImage(image);

        try
        {
            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.White);

            //画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);

            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Gif";
            context.Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
    
    public bool IsReusable {
        get {
            return false;
        }
    }

}
ValidateCode

注意实现IRequiresSessionState方法

注册页面通过<span id="validateCodeMsg" style="font-size: 14px; color: red"></span><img src="/ashx/ValidateCode.ashx" />来实现

3.1 添加枚举,用于区分用户状态

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

namespace BookShopManager.Web.Enum
{
    public enum UserSatateEnum
    {
        NormalState = 1,//正常状态
        InvalidState = 2,//无效状态
        LockState = 3,//锁定/禁用状态
    }
}
枚举

3.2 错误页

using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BookShopManager.Web
{
    public partial class ShowMsg : System.Web.UI.Page
    {
        public string Msg { get; set; }
        public string Title { get; set; }
        public string Url { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
            Msg = string.IsNullOrEmpty(Request["msg"]) ? "暂无信息" : Request["msg"];
            Title = string.IsNullOrEmpty(Request["title"]) ? "商品列表页面" : Request["title"];
            Url = string.IsNullOrEmpty(Request["url"]) ? "/BookList.aspx" : Request["url"];
        }
    }
}
View Code

3.3 注册信息验证

//前台页面

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

<asp:Content ID="Content1" ContentPlaceHolderID="Header" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <link href="../Admin/Css/Register/Register.css" rel="stylesheet" />
    <script src="../js/Register/Register.js"></script>
    <script type="text/javascript">
        $(function () {
            //验证用户名
            $('#LoginId').blur(function () {
                var val = $('#LoginId').val();
                if (isNullOrEmpty(this)) {
                    if (isNamingConventions(this)) {
                        //判断用户名是否存在
                        $.post("/ashx/ValidateReg.ashx", { "action": "name", "loginName": val }, function (data) {
                            $("#msgName").css("display", "inline");
                            warnMsg("#msgName", data);
                        })
                        warnMsg("#msgName", "");
                    } else {
                        warnMsg("#msgName", "用户名只能是数字、字母、下划线 !");
                    }
                } else {
                    warnMsg("#msgName", "用户名不能为空 !");
                }
            });
            //验证姓名
            $('#txtRealName').blur(function () {
                if (isNullOrEmpty(this)) {
                    warnMsg("#msgRealName", "");
                } else {
                    warnMsg("#msgRealName", "真实姓名不能为空 !");
                }
            });
            //验证密码
            $('#txtPwd').blur(function () {
                if (isNullOrEmpty(this)) {
                    warnMsg("#msgPwd", "");
                } else {
                    warnMsg("#msgPwd", "密码不能为空 !");
                }
            });
            //验证确认密码
            $('#txtConfirmPwd').blur(function () {
                if (isNullOrEmpty(this)) {
                    if ($('#txtConfirmPwd').val() != $('#txtPwd').val()) {
                        warnMsg("#msgConfirmPwd", "密码不一致 !");
                    } else {
                        warnMsg("#msgConfirmPwd", "");
                    }
                } else {
                    warnMsg("#msgConfirmPwd", "密码不能为空 !");
                }
            });
            //验证邮箱
            $('#userMail').blur(function () {
                validateEmail();
            });
            //验证地址    
            $('#txtAddress').blur(function () {
                if (isNullOrEmpty(this)) {
                    warnMsg("#msgAddress", "");
                } else {
                    warnMsg("#msgAddress", "地址不能为空 !");
                }
            });
            //验证手机
            $('#txtPhone').blur(function () {
                if (isNullOrEmpty(this)) {
                    if (isNan(this)) {
                        warnMsg("#msgPhone", "");
                    } else {
                        warnMsg("#msgPhone", "手机号只能为数字 !");
                    }
                } else {
                    warnMsg("#msgPhone", "手机号不能为空 !");
                }
            });
            //验证验证码
            $('#validateCode').blur(function () {
                validateCode();
            });
            //注册
            $("#btnRegister").click(function () {
                validateEmail();
                validateCode();
                var par = $("#aspnetForm").serializeArray();
                par = JSON.stringify(par);

                $.post("/ashx/UserRegister.ashx", { "parameter": par }, function (data) {
                    alert(data);
                });
            });

        });
        //验证"邮箱"
        function validateEmail() {
            var val = $('#userMail').val();
            if (val != "") {
                var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                if (reg.test(val)) {
                    //隐藏消息
                    $("#msgEamil").css("display", "none");
                    //发送给Ajax校验
                    $.post("/ashx/ValidateReg.ashx", { "action": "mail", "userMail": val }, function (data) {
                        $("#msgEamil").css("display", "inline");
                        warnMsg("#msgEamil", data);
                    });
                } else {
                    warnMsg("#msgEamil", "邮箱格式错误 !");
                }
            } else {
                warnMsg("#msgEamil", "邮箱不能为空 !");
            }
        };
        //验证"验证码"
        function validateCode() {
            var val = $('#validateCode').val();
            if (val != "") {
                var reg = /^[0-9]*$/;
                if (reg.test(val)) {
                    //隐藏消息
                    $("#validateCodeMsg").css("display", "none");
                    //发送给Ajax校验
                    $.post("/ashx/ValidateReg.ashx", { "action": "code", "validateCode": val }, function (data) {
                        $("#validateCodeMsg").css("display", "inline");
                        warnMsg("#validateCodeMsg", data);
                    });
                } else {
                    warnMsg("#validateCodeMsg", "验证码格式错误 !");
                }
            } else {
                warnMsg("#validateCodeMsg", "验证码不能为空 !");
            }
        };
        //显示警告
        function warnMsg(span, msg) {
            if (span != null) {
                $(span).text(msg);
            }
        }

    </script>
<form id="formRegister" name="formRegister" method="post">
    <table width="80%" height="22" border="0" align="center" cellpadding="0" cellspacing="0" id="tableRegister">
        <tr>
            <td width="2" bgcolor="#DDDDCC">&nbsp;</td>
            <td>
                <div align="center">
                    <table height="61" cellpadding="0" cellspacing="0" style="height: 332px">
                        <tr>
                            <td height="33" colspan="6">
                                <p class="STYLE2" style="text-align: center">注册新帐户方便又容易</p>
                            </td>
                        </tr>
                        <tr>
                            <td width="24%" align="center" valign="top" style="height: 26px">用户名</td>
                            <td valign="top" width="37%" align="left" style="height: 26px">
                                <input type="text" name="LoginId" id="LoginId" />
                                <span id="msgName" style="font-size: 14px; color: red">*</span>
                            </td>
                        </tr>
                        <tr>
                            <td width="24%" height="26" align="center" valign="top">真实姓名:</td>
                            <td valign="top" width="37%" align="left">
                                <input type="text" name="txtRealName" id="txtRealName" />
                                <span id="msgRealName" style="font-size: 14px; color: red">*</span>
                            </td>
                        </tr>
                        <tr>
                            <td width="24%" height="26" align="center" valign="top">密码:</td>
                            <td valign="top" width="37%" align="left">
                                <input type="password" name="txtPwd" id="txtPwd" />
                                <span id="msgPwd" style="font-size: 14px; color: red">*</span>
                            </td>
                        </tr>
                        <tr>
                            <td width="24%" height="26" align="center" valign="top">确认密码:</td>
                            <td valign="top" width="37%" align="left">
                                <input type="password" name="txtConfirmPwd" id="txtConfirmPwd" />
                                <span id="msgConfirmPwd" style="font-size: 14px; color: red">*</span>
                            </td>
                        </tr>
                        <tr>
                            <td width="24%" height="26" align="center" valign="top">Email:</td>
                            <td valign="top" width="37%" align="left">
                                <input type="text" name="txtEmail" id="userMail" />
                                <span id="msgEamil" style="font-size: 14px; color: red">*</span>

                            </td>
                        </tr>
                        <tr>
                            <td width="24%" height="26" align="center" valign="top">地址:</td>
                            <td valign="top" width="37%" align="left">
                                <input type="text" name="txtAddress" id="txtAddress" />
                                <span id="msgAddress" style="font-size: 14px; color: red">*</span>
                            </td>
                        </tr>
                        <tr>
                            <td width="24%" height="26" align="center" valign="top">手机:</td>
                            <td valign="top" width="37%" align="left">
                                <input type="text" name="txtPhone" id="txtPhone" />
                                <span id="msgPhone" style="font-size: 14px; color: red">*</span>
                            </td>
                        </tr>
                        <tr>
                            <td width="24%" align="center" valign="top" class="auto-style1">验证码:</td>
                            <td valign="top" width="37%" align="left" class="auto-style1">
                                <input type="text" name="txtCode" id="validateCode" />
                                <span id="validateCodeMsg" style="font-size: 14px; color: red">*</span>
                                <img src="/ashx/ValidateCode.ashx" /></td>
                        </tr>
                        <tr>
                            <td colspan="2" align="center">
                                <input type="button" value="注册" class="regnow" id="btnRegister" /></td>
                        </tr>
                        <tr>
                            <td colspan="2" align="center">&nbsp;</td>
                        </tr>
                    </table>
                    <div class="STYLE5">---------------------------------------------------------</div>
                </div>
            </td>
            <td width="2" bgcolor="#DDDDCC">&nbsp;</td>
        </tr>
    </table>
</form>
    

</asp:Content>
前台页面

//通过ajax页面验证

using BookShopManager.Web.Common;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;

namespace BookShopManager.Web.Ashx
{
    /// <summary>
    /// ValidateReg 的摘要说明
    /// 前台页面校验
    /// </summary>
    public class ValidateReg : IHttpHandler, IRequiresSessionState
    {

        BLL.Users UserManager = new BLL.Users();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];
            if (action == "mail")
            {
                CheckedUserMail(context);
            }
            else if (action == "code")
            {
                string validateCode = context.Request["validateCode"];
                if (ValidateCode.CheckValidateCode(validateCode))
                {
                    context.Response.Write("");
                }
                else
                {
                    context.Response.Write("验证码错误");
                }
            }
            else if (action == "name") {
                string loginName = context.Request["loginName"];
                if (UserManager.ExistsByUserName(loginName))
                {
                    context.Response.Write("用户名已存在");
                }
                else
                {
                    context.Response.Write("");
                }
            }

        }

        #region 校验邮箱
        private void CheckedUserMail(HttpContext context)
        {
            string userMail = context.Request["userMail"];
            if (UserManager.ExistsByUserMail(userMail))
            {
                context.Response.Write("邮箱已使用");
            }
            else
            {
                context.Response.Write("");
            }
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

//点击"注册"按钮进行验证

using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using BookShopManager.Web.Common;
using BookShopManager.BLL;
using System.Web.SessionState;
using BookShopManager.Web.Enum;
using System.Web.UI;


namespace BookShopManager.Web.Ashx
{
    /// <summary>
    /// UserRegister 的摘要说明
    /// 注册按钮后 进行"校验"和"新增"
    /// </summary>
    public class UserRegister : IHttpHandler, IRequiresSessionState
    {
        //"用户注册"服务端校验
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string strJson = context.Request["parameter"];
            Model.Users userInfo;
            BLL.Users userManager = new BLL.Users();
            string msg = string.Empty;
            if (ValidateUserInfo(strJson, out msg, out userInfo))
            {
                //校验成功,进行添加
                if (userManager.Add(userInfo) > 0)
                {
                    string strScript = "<script type='text/javascript'>alert('" + "注册成功" + "');window.location.href='" + "../Default.aspx" + "'</script>";
                    HttpContext.Current.Session["vCode"] = null;
                    context.Session["userInfo"] = userInfo;
                    context.Response.Redirect("<script type='text/javascript'>alert('" + "注册成功" + "');</script>");

                }
                else
                {
                    //跳到错误页面
                    context.Response.Redirect("/ShowMsg.aspx?msg=" + "注册失败" + "&title=首页" + "&url=/Default.aspx");
                }
            }
            else {
                context.Response.Write(msg);
            }
        }

        private bool ValidateUserInfo(string jsonStr,out string msg, out Model.Users UserInfo)
        {
            JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr);
            UserInfo = new Model.Users();
            BLL.Users UserManager = new BLL.Users();
            UserInfo.LoginId = ja[1]["value"].ToString();           //用户名   
            UserInfo.Name = ja[2]["value"].ToString();          //真实姓名   
            UserInfo.LoginPwd = ja[3]["value"].ToString();    //密码:   
            string confirmPwd = ja[4]["value"].ToString();    //确认密码   
            UserInfo.Address = ja[6]["value"].ToString();     //地址: 
            UserInfo.Phone = ja[7]["value"].ToString();    //手机: 
            UserInfo.Mail = ja[5]["value"].ToString();    //Email:  
            string validate = ja[8]["value"].ToString();    //验证码:
            msg = string.Empty;
            if (string.IsNullOrEmpty(UserInfo.LoginId))
            {
                msg += "用户名不能为空!! \n";
            }
            if (string.IsNullOrEmpty(UserInfo.Name))
            {
                msg += "真实姓名不能为空!! \n";
            }
            if (string.IsNullOrEmpty(UserInfo.LoginPwd))
            {
                msg += "密码不能为空!!\n ";
            }
            if (string.IsNullOrEmpty(confirmPwd))
            {
                msg += "确认密码不能为空!!\n ";
            }
            if (string.IsNullOrEmpty(UserInfo.Address))
            {
                msg += "地址不能为空!!\n ";
            }
            if (string.IsNullOrEmpty(UserInfo.Phone))
            {
                msg += "手机号不能为空!!\n ";
            }
            if (string.IsNullOrEmpty(UserInfo.Mail))
            {
                msg += "邮箱不能为空!!\n ";
            }
            if (string.IsNullOrEmpty(validate))
            {
                msg += "验证码不能为空!!\n ";
            }
            if (msg.Length > 1)
            {
                return false;
            }
            //判断密码是否一致
            if (UserInfo.LoginPwd != confirmPwd)
            {
                msg += "两次密码输入不一致!! \n";
                return false;

            }
            //校验验证码是否正确
            if (!ValidateCode.CheckValidateCode(validate))
            {
                msg += "验证码不正确!! \n";
                return false;
            }
            //校验邮箱是否已使用,
            if (UserManager.ExistsByUserMail(UserInfo.Mail))
            {
                msg += "邮箱已使用!! \n";
                return false;
            }
            //用户名是否存在
            if (UserManager.ExistsByUserName(UserInfo.LoginId))
            {
                msg += "用户名已存在!! \n";
                return false;
            }
            UserInfo.UserStateId = ConvertHelper.ToInt(UserSatateEnum.NormalState.GetHashCode());
            return true;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        bool IHttpHandler.IsReusable
        {
            get { throw new NotImplementedException(); }
        }
    }
}
View Code

注意:在ashx中使用HttpContext.Current.Session["vCode"] ,需要实现IRequiresSessionState接口

posted @ 2017-08-29 07:30  逍遥小天狼  阅读(195)  评论(0编辑  收藏  举报