开发工具: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: Loginpublic 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” 作为缓存的keyvar verifyCodeKey = $"{this.GetType().FullName}_verifyCode";cache.Remove(verifyCodeKey);cache.Insert(verifyCodeKey, verifyCode);#endregionMemoryStream 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” 作为缓存的keyCache 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: Loginpublic 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” 作为缓存的keyCache 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” 作为缓存的keyvar verifyCodeKey = $"{this.GetType().FullName}_verifyCode";cache.Remove(verifyCodeKey);cache.Insert(verifyCodeKey, verifyCode);#endregionMemoryStream memory = new MemoryStream();bitmap.Save(memory, ImageFormat.Gif);return File(memory.ToArray(), "image/gif");}}
}

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

  1. SpringBoot+Vue项目中实现登录验证码校验

    SpringBoot+Vue项目中实现登录验证码校验 在各大项目中,为保证数据的安全性,通常在登录页面加入验证码校验,以防止爬虫带来的数据泄露危机.本文将介绍在前后端分离的项目中,怎样实现图形验证码校 ...

  2. 使用filter过滤器实现简单用户登录验证(不用配置web.xml文件)

    一.filter过滤器的作用 如果想要获取中文字符,或者是显示提交的中文,就需要添加以下代码,来防止乱码的情况发生. request.setCharacterEncoding("utf-8& ...

  3. 数据库用户登录验证及注册功能实现

    数据库用户登录验证及注册功能实现 1.mysql数据库安装 2.解决navicat连接mysql的密码错误问题 3.创建数据库.用户表.插入数据 (1)进入mysql数据库 (2) 创建数据库dnn_ ...

  4. 简单Flask登录验证

    记录一下学习Flask的过程 下面是一个简单的FLask的登录验证代码 from flask import Flask from flask import requestapp = Flask(__n ...

  5. Ajax实现简单的登录验证与帐号注册

    上一篇博客介绍了Ajax的GET和POST方法以及上传文件的进度条展示,这篇博客将介绍一个简单的登录与注册功能的实现 设计HTML 这个是即将成为我毕业设计的一个网站, 在导航栏我添加了两个注册和登录 ...

  6. Android 实训 Day2——项目实战(简单的登录页面)

    1.首先,我们准备好需要用的图片,这里我只用了四张照片,分别是用户头像,用户名图标,密码图标,容器背景. 将照片粘贴到res/mipmap 目录,或者res/drawble目录下: 新建一个Empty ...

  7. 注册登录案例用MVC和mysql_用MVC模式实现简单用户登录注册功能

    Model2模式 Jsp+Servlet+JavaBean MVC:开发模式 M:Model 模型层 ----> JavaBean V:View 视图层 ----> Jsp C:Contr ...

  8. vue2.0实战项目——简单的快餐店系统

    最近学习vue看到网上很多学习的资料,就找了一个项目系统练习,主要是想学习了的一些知识点,系统的组合运用一遍.网上根据技术胖老师博客的内容自己也实战了一遍,挺实用的,对vue框架有了更深入的了解以及自 ...

  9. C# .net MVC 实战项目 使用wangEditor实现word在线编辑 + 导出到word文档(解决html图片导出到word是个大红叉问题) (六)

    经过各方面的资源查询和不懈的研究,困扰本人一个多星期的问题终于解决. 先上效果图 添加一些文本和图片 点击确认提交,将内容添加到word并下载 打开 提示.警告: 一开始找到使用 Aspose.Wor ...

最新文章

  1. Pytorch完成基础的模型-线性回归
  2. 能打开java文件_用java打开一个本地文件
  3. python编译为c_cython编译Python为c语言
  4. [翻译]为什么你不要收缩数据库文件
  5. php中文件下载,PHP中文件下载
  6. wxWidgets:wxRibbonButtonBar类用法
  7. ES5-拓展 箭头函数的this、this的优先级
  8. window系统盘瘦身(开发)
  9. PCB常用度量衡单位
  10. 设计模式在项目中的应用案例_项目化学习案例(五):菊花种植的秘密——项目化学习在菊种植课程中的应用设计案例...
  11. WIN7部分程序中文乱码的简单解决方法
  12. ubuntu遇到的 the system is runing low-graphics mode 问题
  13. 网络管理助力节约IT运维成本
  14. 高速串行总线技术发展与应用分析
  15. pythonforandroid下载中文_SL4A、PythonForAndroid和Android 7.0 Noug
  16. 服务器维护封号,LOL客服的关于他们自己服务器问题导致账号被封号的问题
  17. 论文笔记:Geneva、Themis、SymTCP、TCP-Fuzz
  18. 为什么要用VR全景?5个答案告诉你
  19. PaddlePaddle七日训练营心得体会
  20. matlab限幅滤波法,几种常用的滤波方法

热门文章

  1. java字典初始化_字典翻译注解讲解
  2. Java实现单例模式(懒汉式和饿汉式)
  3. Promise的理解与使用(收藏版)
  4. 【报告分享】2021中国小吃数字化推广度指数报告-饿了么x阿里巴巴(附下载)
  5. 浅析:领域模型、贫血模型和充血模型
  6. 计算机毕业设计ssm动物防疫信息管理
  7. world计算机恢复出厂设置,互联网常识普及:刷机和恢复出厂设置有什么不同
  8. 使用gitbook editor管理个人笔记/制作PDF电子书
  9. webstorm报错:TS2307: Cannot find module ‘./App.vue‘ or its corresponding type declarations
  10. C8051F396 ADC操作