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

2022年11月5日11:25:37

开发工具:VS2015
框架 .net MVC

效果图
C# .net mvc 实战项目 简单的登录验证和注册
C# .net mvc 实战项目 简单的登录验证和注册

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

publicclassVerifyCodeHelper{publicstaticBitmapCreateVerifyCode(outstring code){//建立Bitmap对象,绘图Bitmap bitmap=newBitmap(200,60);Graphics graph= Graphics.FromImage(bitmap);
            graph.FillRectangle(newSolidBrush(Color.White),0,0,200,60);Font font=newFont(FontFamily.GenericSerif,48, FontStyle.Bold, GraphicsUnit.Pixel);Random r=newRandom();string letters="ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";StringBuilder sb=newStringBuilder();//添加随机的四个字母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,newSolidBrush(Color.Black), x*38, r.Next(0,15));}
            code= sb.ToString();//混淆背景Pen linePen=newPen(newSolidBrush(Color.Black),2);for(int x=0; x<6; x++)
                graph.DrawLine(linePen,newPoint(r.Next(0,199), r.Next(0,59)),newPoint(r.Next(0,199), r.Next(0,59)));return bitmap;}}

添加LoginController控制器

publicclassLoginController:Controller{// GET: LoginpublicActionResultIndex(){returnView();}}

添加VerifyCode方法

/// <summary>/// 提供验证码/// </summary>/// <returns></returns>publicActionResultVerifyCode(){string verifyCode=string.Empty;Bitmap bitmap= App_Start.VerifyCodeHelper.CreateVerifyCode(out verifyCode);#region 缓存KeyCache cache=newCache();// 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的keyvar verifyCodeKey=$"{this.GetType().FullName}_verifyCode";
            cache.Remove(verifyCodeKey);
            cache.Insert(verifyCodeKey, verifyCode);#endregionMemoryStream memory=newMemoryStream();
            bitmap.Save(memory, ImageFormat.Gif);returnFile(memory.ToArray(),"image/gif");}

右键,添加Index视图
C# .net mvc 实战项目 简单的登录验证和注册
视图代码

@{
    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>functionchangecode(){
                $('#verifycode').attr('src', '/Login/VerifyCode?t='+newDate().getSeconds());}</script><div style="margin-top:20px"><input type="submit"value="登录" name="login"/><input type="submit"value="注册" name="login"/></div></div>}</body>

C# .net mvc 实战项目 简单的登录验证和注册
在控制器中写登录方法

[HttpPost]publicActionResultIndex(string login,string verifyCode){if(login=="注册"){returnView("Register");}string username= Request["username"];string password= Request["password"];if(string.IsNullOrEmpty(username)||string.IsNullOrEmpty(password)){returnContent("<script>alert('账号密码不能为空');location.href='Login/Index'</script>");}// 第一步检验验证码// 从缓存获取验证码作为校验基准// 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的keyCache cache=newCache();var verifyCodeKey=$"{this.GetType().FullName}_verifyCode";object cacheobj= cache.Get(verifyCodeKey);if(cacheobj==null){returnContent("<script>alert('验证码已失效');location.href='Login/Index'</script>");}//不区分大小写比较验证码是否正确elseif(!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase))){returnContent("<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//登录成功跳转returnRedirectToAction("Index","Main");}else{returnContent("<script>alert('输入有误');location.href='Login/Index'</script>");}}

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

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

添加注册代码

先添加注册的控制器

publicActionResultRegister(){returnView();}

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

完整控制器代码

usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.Drawing.Imaging;usingSystem.IO;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Caching;usingSystem.Web.Mvc;namespaceDSG_Analyse.Controllers{publicclassLoginController:Controller{// GET: LoginpublicActionResultIndex(){returnView();}[HttpPost]publicActionResultIndex(string login,string verifyCode){if(login=="注册"){returnView("Register");}string username= Request["username"];string password= Request["password"];if(string.IsNullOrEmpty(username)||string.IsNullOrEmpty(password)){returnContent("<script>alert('账号密码不能为空');location.href='Login/Index'</script>");}// 第一步检验验证码// 从缓存获取验证码作为校验基准// 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的keyCache cache=newCache();var verifyCodeKey=$"{this.GetType().FullName}_verifyCode";object cacheobj= cache.Get(verifyCodeKey);if(cacheobj==null){returnContent("<script>alert('验证码已失效');location.href='Login/Index'</script>");}//不区分大小写比较验证码是否正确elseif(!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase))){returnContent("<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//登录成功跳转returnRedirectToAction("Index","Main");}else
  • 作者:C#Code- Sheep
  • 原文链接:https://blog.csdn.net/weixin_39448579/article/details/120309389
    更新时间:2022年11月5日11:25:37 ,共 6885 字。