栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

开发工具: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方法

        /// 
        /// 提供验证码
        /// 
        /// 
        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 = "用户登录";
}

    @using (Html.BeginForm("Index", "Login"))
    {
        

@Html.Label("用户名") @Html.TextBox("username")

@Html.Label("密码") @Html.Password("password")

@Html.Label("验证码") @Html.TextBox("verifyCode")

}


在控制器中写登录方法

[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("");
            }
            // 第一步检验验证码
            // 从缓存获取验证码作为校验基准  
            // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
            Cache cache = new Cache();
            var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
            object cacheobj = cache.Get(verifyCodeKey);
            if (cacheobj == null)
            {
                return Content("");
            }//不区分大小写比较验证码是否正确
            else if (!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase)))
            {
                return Content("");
            }
            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("");
            }
        }

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

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

添加注册代码

先添加注册的控制器

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

添加Register视图

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

用户注册 @using (Html.BeginForm("Register", "User")) {

@Html.Label("用户名") @Html.TextBox("username")

@Html.Label("密码") @Html.Password("password")

@Html.Label("确认密码")

}

添加注册的方法

 [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("");
            }
            if(!string.Equals(password, confirmpassword))
                return Content("");
            if (App_Start.RedisHelper.HasContains("user", username))
            {
                return Content("");
            }
            App_Start.RedisHelper.SetHas("user", username, password);
            //默认注册的都是操作员
            App_Start.RedisHelper.SetString(username, "0");
            return Content("");
        }

完整控制器代码

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("");
            }
            // 第一步检验验证码
            // 从缓存获取验证码作为校验基准  
            // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
            Cache cache = new Cache();
            var verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
            object cacheobj = cache.Get(verifyCodeKey);
            if (cacheobj == null)
            {
                return Content("");
            }//不区分大小写比较验证码是否正确
            else if (!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase)))
            {
                return Content("");
            }
            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("");
            }
        }
        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("");
            }
            if(!string.Equals(password, confirmpassword))
                return Content("");
            if (App_Start.RedisHelper.HasContains("user", username))
            {
                return Content("");
            }
            App_Start.RedisHelper.SetHas("user", username, password);
            //默认注册的都是操作员
            App_Start.RedisHelper.SetString(username, "0");
            return Content("");
        }

        /// 
        /// 提供验证码
        /// 
        /// 
        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");
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/904057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号