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

开发工具:VS2015
框架 .net MVC

效果图
C# .net mvc 实战项目 简单的登录验证和注册 (一)_第1张图片
C# .net mvc 实战项目 简单的登录验证和注册 (一)_第2张图片

先实现验证码
在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 = "用户登录";
}
<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("");
            }
            // 第一步检验验证码
            // 从缓存获取验证码作为校验基准  
            // 先用当前类的全名称拼接上字符串 “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 = "用户注册";
}

<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 = "";
            document.getElementById("submit").disabled = false;
        }
        else
        {
            document.getElementById("tishi").innerHTML = "两次密码不相同";
            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("");
            }
            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");
        }
    }
}

你可能感兴趣的:(MVC,C#,c#,mvc,.net)