C# .net mvc 实战项目 简单的登录验证和注册 (一)

8 篇文章 4 订阅

开发工具:VS2015
框架 .net MVC

效果图
在这里插入图片描述
在这里插入图片描述

先实现验证码
在App_Start文件夹中,添加类VerifyCodeHelper

public class VerifyCodeHelper
    {
        public static Bitmap CreateVerifyCode(out string code)
        {
            //建立Bitmap对象,绘图
            Bitmap bitmap = new Bitmap(200, 60);
            Graphics graph = Graphics.FromImage(bitmap);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
            Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
            Random r = new Random();
            string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
            StringBuilder sb = new StringBuilder();
            //添加随机的四个字母
            for (int x = 0; x < 4; x++)
            {
                string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
                sb.Append(letter);
                graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
            }
            code = sb.ToString();

            //混淆背景
            Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
            for (int x = 0; x < 6; x++)
                graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
            return bitmap;
        }
    }

添加LoginController控制器

 public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }
    }

添加VerifyCode方法

        /// <summary>
        /// 提供验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult VerifyCode()
        {
            string verifyCode = string.Empty;
            Bitmap bitmap = App_Start.VerifyCodeHelper.CreateVerifyCode(out verifyCode);
            #region 缓存Key 
            Cache cache = new Cache();
            // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
            var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
            cache.Remove(verifyCodeKey);
            cache.Insert(verifyCodeKey, verifyCode);
            #endregion
            MemoryStream memory = new MemoryStream();
            bitmap.Save(memory, ImageFormat.Gif);
            return File(memory.ToArray(), "image/gif");
        }

右键,添加Index视图
在这里插入图片描述
视图代码

@{
    ViewBag.Title = "用户登录";
}
<body style="text-align:center">
    @using (Html.BeginForm("Index", "Login"))
    {
        <div style="margin-top:100px">
            <div>
                <p>
                    @Html.Label("用户名")
                    @Html.TextBox("username")
                </p>
            </div>
            <div>
                <p>
                    @Html.Label("密码")
                    @Html.Password("password")
                </p>
            </div>
            <div>
                <p>
                    @Html.Label("验证码")
                    @Html.TextBox("verifyCode")
                </p>
            </div>
            <div>
                <img id="verifycode" title="更换验证码" style="height: 36px;
                width: 108px;
                margin-left: -15px;
                margin-top: -8px;
                cursor: pointer;" src="@Url.Action("VerifyCode")" οnclick="changecode()" />
            </div>
            <script>
            function changecode() {
                $('#verifycode').attr('src', '/Login/VerifyCode?t=' + new Date().getSeconds());
            }
            </script>
            <div style="margin-top:20px">
                <input type="submit" value="登录" name="login" />
                <input type="submit" value="注册" name="login" />
            </div>
        </div>
    }
</body>

在这里插入图片描述
在控制器中写登录方法

[HttpPost]
        public ActionResult Index(string login, string verifyCode)
        {
            if (login == "注册")
            {
                return View("Register");
            }
            string username = Request["username"];
            string password = Request["password"];
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return Content("<script>alert('账号密码不能为空');location.href='Login/Index'</script>");
            }
            // 第一步检验验证码
            // 从缓存获取验证码作为校验基准  
            // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
            Cache cache = new Cache();
            var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
            object cacheobj = cache.Get(verifyCodeKey);
            if (cacheobj == null)
            {
                return Content("<script>alert('验证码已失效');location.href='Login/Index'</script>");
            }//不区分大小写比较验证码是否正确
            else if (!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase)))
            {
                return Content("<script>alert('验证码错误');location.href='Login/Index'</script>");
            }
            cache.Remove(verifyCodeKey);
            //...接下来再进行账号密码比对等登录操作                    
            string ps = App_Start.RedisHelper.GetHas("user", username);
            if (App_Start.RedisHelper.GetHas("user", username) == password)
            {
                //获取登录的用户权限
                string s = App_Start.RedisHelper.GetString(username);
                Session["auther"] = App_Start.RedisHelper.GetString(username);//管理员为1,非管理员为0                
                //登录成功跳转               
                return RedirectToAction("Index", "Main");
            }
            else
            {
                return Content("<script>alert('输入有误');location.href='Login/Index'</script>");
            }
        }

账号密码对比是存于我的Redis之中,从Redis之中去进行验证。

有兴趣的可以参考我之前的博文:运用Redis

添加注册代码

先添加注册的控制器

public ActionResult Register()
        {
            return View();
        }

添加Register视图


@{
    ViewBag.Title = "用户注册";
}

<h2>用户注册</h2>
@using (Html.BeginForm("Register", "User"))
{
    <form>
        <div style="margin-top:100px;text-align:center">
            <div>
                <p>
                    @Html.Label("用户名")
                    @Html.TextBox("username")
                </p>
            </div>
            <div>
                <p>
                    @Html.Label("密码")
                    @Html.Password("password")
                </p>
            </div>
            <div>
                <p>
                    @Html.Label("确认密码")
                    <input type="password" id="confirmpassword" name="confirmpassword" onkeyup="validate()">
                    <span id="tishi"></span>
                </p>
            </div>
            <div style="margin-top:20px">
                <input type="submit" value="返回" id="Register" name="Register" />
                <input type="submit" value="注册" id="Register" name="Register" />
            </div>
        </div>
    </form>
}
<script>
    function validate()
    {
        var pw1 = document.getElementById("password").value;
        var pw2 = document.getElementById("confirmpassword").value;
        if (pw1 == pw2)
        {
            document.getElementById("tishi").innerHTML = "<font color='green'></font>";
            document.getElementById("submit").disabled = false;
        }
        else
        {
            document.getElementById("tishi").innerHTML = "<font color='red'>两次密码不相同</font>";
            document.getElementById("submit").disabled = true;
        }
    }
</script>

添加注册的方法

 [HttpPost]
        public ActionResult Register(string Register, string username, string password)//注册
        {
             if (Register == "返回")
            {
                return View("Index");
            }
            username = Request["username"];
            password = Request["password"];
            confirmpassword= Request["confirmpassword"];          
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(confirmpassword))
            {
                return Content("<script>alert('账号密码不能为空');location.href='Register'</script>");
            }
            if(!string.Equals(password, confirmpassword))
                return Content("<script>alert('两次密码输入不同');location.href='Register'</script>");
            if (App_Start.RedisHelper.HasContains("user", username))
            {
                return Content("<script>alert('用户名已经存在');location.href='Register'</script>");
            }
            App_Start.RedisHelper.SetHas("user", username, password);
            //默认注册的都是操作员
            App_Start.RedisHelper.SetString(username, "0");
            return Content("<script>alert('注册成功');location.href='Index'</script>");
        }

完整控制器代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;

namespace DSG_Analyse.Controllers
{
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string login, string verifyCode)
        {
            if (login == "注册")
            {
                return View("Register");
            }
            string username = Request["username"];
            string password = Request["password"];
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return Content("<script>alert('账号密码不能为空');location.href='Login/Index'</script>");
            }
            // 第一步检验验证码
            // 从缓存获取验证码作为校验基准  
            // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
            Cache cache = new Cache();
            var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
            object cacheobj = cache.Get(verifyCodeKey);
            if (cacheobj == null)
            {
                return Content("<script>alert('验证码已失效');location.href='Login/Index'</script>");
            }//不区分大小写比较验证码是否正确
            else if (!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase)))
            {
                return Content("<script>alert('验证码错误');location.href='Login/Index'</script>");
            }
            cache.Remove(verifyCodeKey);
            //...接下来再进行账号密码比对等登录操作                    
            string ps = App_Start.RedisHelper.GetHas("user", username);
            if (App_Start.RedisHelper.GetHas("user", username) == password)
            {
                //获取登录的用户权限
                string s = App_Start.RedisHelper.GetString(username);
                Session["auther"] = App_Start.RedisHelper.GetString(username);//管理员为1,非管理员为0                
                //登录成功跳转               
                return RedirectToAction("Index", "Main");
            }
            else
            {
                return Content("<script>alert('输入有误');location.href='Login/Index'</script>");
            }
        }
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(string Register, string username, string password,string confirmpassword)//注册
        {
            if (Register == "返回")
            {
                return View("Index");
            }
            username = Request["username"];
            password = Request["password"];
            confirmpassword= Request["confirmpassword"];          
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(confirmpassword))
            {
                return Content("<script>alert('账号密码不能为空');location.href='Register'</script>");
            }
            if(!string.Equals(password, confirmpassword))
                return Content("<script>alert('两次密码输入不同');location.href='Register'</script>");
            if (App_Start.RedisHelper.HasContains("user", username))
            {
                return Content("<script>alert('用户名已经存在');location.href='Register'</script>");
            }
            App_Start.RedisHelper.SetHas("user", username, password);
            //默认注册的都是操作员
            App_Start.RedisHelper.SetString(username, "0");
            return Content("<script>alert('注册成功');location.href='Index'</script>");
        }

        /// <summary>
        /// 提供验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult VerifyCode()
        {
            string verifyCode = string.Empty;
            Bitmap bitmap = App_Start.VerifyCodeHelper.CreateVerifyCode(out verifyCode);
            #region 缓存Key 
            Cache cache = new Cache();
            // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
            var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
            cache.Remove(verifyCodeKey);
            cache.Insert(verifyCodeKey, verifyCode);
            #endregion
            MemoryStream memory = new MemoryStream();
            bitmap.Save(memory, ImageFormat.Gif);
            return File(memory.ToArray(), "image/gif");
        }
    }
}
  • 7
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yangzm996

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值