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

.NETMVC5登录页面及验证码功能

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

.NETMVC5登录页面及验证码功能

1.成品截图

文件结构如图:

 

2.创建Helper文件夹

1.在项目中创建Helper文件夹,并在文件夹内创建AjaxResult.cs,Json.cs和VerrifyCode.cs文件,代码分别如下:

AjaxResult.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ContosoUniversity.Helper
{
    public class AjaxResult
    {
        /// 
        /// 操作结果类型
        /// 
        public object state { get; set; }
        /// 
        /// 获取 消息内容
        /// 
        public string message { get; set; }
        /// 
        /// 获取 返回数据
        /// 
        public object data { get; set; }
    }
    /// 
    /// 表示 ajax 操作结果类型的枚举
    /// 
    public enum ResultType
    {
        /// 
        /// 消息结果类型
        /// 
        info,
        /// 
        /// 成功结果类型
        /// 
        success,
        /// 
        /// 警告结果类型
        /// 
        warning,
        /// 
        /// 异常结果类型
        /// 
        error
    }
}

Json.cs代码如下:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace ContosoUniversity.Helper
{
    public static class Json
    {
        public static object ToJson(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject(Json);
        }
        public static string ToJson(this object obj)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static string ToJson(this object obj, string datetimeformats)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static T ToObject(this string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject(Json);
        }
        public static List ToList(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject>(Json);
        }
        public static DataTable ToTable(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject(Json);
        }
        public static JObject ToJObject(this string Json)
        {
            return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
        }
    }
}

VerifyCode.cs代码如下:

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

namespace ContosoUniversity.Helper
{
    public class VerifyCode
    {
        public string CreateValidateCode()
        {
            //验证码的字符集,去掉了一些容易混淆的字符 
            char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            string chkCode = string.Empty;
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            return chkCode;

        }
        public byte[] GetVerifyCode(string chkCode)
        {
            int codeW = 80;
            int codeH = 30;
            int fontSize = 16;
            
            //颜色列表,用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表,用于验证码 
            string[] font = { "Times New Roman" };
            Random rnd = new Random();
            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 3; i++)
            {
                int x1 = rnd.Next(codeW);
                int y1 = rnd.Next(codeH);
                int x2 = rnd.Next(codeW);
                int y2 = rnd.Next(codeH);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
            }
            //将验证码图片写入内存流,并将其以 "image/Png" 格式输出 
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }
        }
    }
}
3.创建LocalStyle文件

1.在项目文件内创建LocalStyle文件

2.在LocalStyle文件夹内分别创建CSS和Javascript文件

3.在CSS文件夹内创建LoginStyle.css文件

4.在Javascript文件下创建LoginScript.js文件

LoginStyle.css文件代码如下:

@import url(http://fonts.googleapis.com/css?family=Tenor+Sans);

html {
	background-color: #5D92BA;
	font-family: "Tenor Sans", sans-serif;
}

.container {
	width: 500px;
	height: 400px;
	margin: 0 auto;
}

.login {
	
	margin-top: 30%;
	width: 450px;
}

.login-heading {
	font: 1.8em/48px "Tenor Sans", sans-serif;
	color: white;
}

.input-txt {
	width: 100%;
	padding: 20px 10px;
	background: #5D92BA;
	border: none;
	font-size: 1em;
	color: white;
	border-bottom: 1px dotted rgba(250, 250, 250, 0.4);
	-moz-box-sizing: border-box;
	-webkit-box-sizing: border-box;
	box-sizing: border-box;
	-moz-transition: background-color 0.5s ease-in-out;
	-o-transition: background-color 0.5s ease-in-out;
	-webkit-transition: background-color 0.5s ease-in-out;
	transition: background-color 0.5s ease-in-out;
}

	.input-txt:-moz-placeholder {
		color: #81aac9;
	}

	.input-txt:-ms-input-placeholder {
		color: #81aac9;
	}

	.input-txt::-webkit-input-placeholder {
		color: #81aac9;
	}

	.input-txt:focus {
		background-color: #4478a0;
	}

.login-footer {
	margin: 10px 0;
	overflow: hidden;
	float: left;
	width: 100%;
}

.btn {
	padding: 15px 30px;
	border: none;
	background: white;
	color: #5D92BA;
}

.btn--right {
	float: right;
}

.icon {
	display: inline-block;
}

.icon--min {
	font-size: .9em;
}

.lnk {
	font-size: .8em;
	line-height: 3em;
	color: white;
	text-decoration: none;
}

LoginScript.js文件代码如下:

(function ($) {
    $.login = {

        formMessage: function (msg) {
            $('.login_tips').find('.tips_msg').remove();
            $('.login_tips').append('' + msg + '');
        },

        loginClick: function () {
            var $username = $("#username");
            var $password = $("#password");
            var $code = $("#validateCode");
            if ($username.val() == "") {
                $username.focus();
                $.login.formMessage('请输入用户名');

                return false;
            }
            else if ($password.val() == "") {
                $password.focus();
                $.login.formMessage('请输入登录密码');

                return false;
            }
            else if ($code.val() == "") {
                $code.focus();
                $.login.formMessage('请输入验证码');

                return false;
            }
            else {

                $.login.formMessage('');
                $("#loginButton").attr('disabled', 'disabled').find('span').html("验证中...");
                $.ajax({
                    url: "/Login/CheckLogin",
                    data: { username: $.trim($username.val()), password: $.trim($password.val()), code: $.trim($code.val()) },
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            $("#loginButton").find('span').html("登录成功,正在跳转...");
                            window.setTimeout(function () {
                                window.location.href = "/Student/Index";
                            }, 500);
                        }
                        else {
                            $("#loginButton").removeAttr('disabled').find('span').html("登录");
                            $("#switchCode").trigger("click");
                            $code.val('');
                            $.login.formMessage(data.message);
                        }
                    }
                });
            }
        },

        init: function () {
            $("#switchCode").click(function () {
                $("#imgCode").attr("src", "/Login/GetAuthCode?time=" + Math.random());
            });
            $("#loginButton").click(function () {
                $.login.loginClick();
            });
        }

    };
    $(function () {
        $.login.init();
    });
})(jQuery);

 4.创建LoginController.cs文件

LoginController.cs代码如下:

using ContosoUniversity.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContosoUniversity.DAL;
using ContosoUniversity.Models;

namespace ContosoUniversity.Controllers
{
    public class LoginController : Controller
    {
        private LoginContext db = new LoginContext();   //连接数据库
        // GET: Login       
        public ActionResult Index()
        {
            return View();
        }
        //退出登入功能,不用的话可删掉
        public ActionResult Exits()
        {
            
            Session["UserName"] = null;
            return RedirectToAction("Index");   //重新运行导向其他方法,此处为导向首页
        }
        //获取验证码
        public ActionResult GetAuthCode()
        {
            VerifyCode vCode = new VerifyCode();
            string code = vCode.CreateValidateCode();
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.GetVerifyCode(code);
            return File(bytes, @"image/jpeg");
        }
        public ActionResult CheckLogin(string username, string password, string code)
        {
            bool Exists = db.Accounts.Any(u => u.username == username);
            try
            {
                if (!Exists)
                {
                    return Content(new AjaxResult { state = ResultType.error.ToString(), message = "账号不存在!" }.ToJson());
                }
                else 
                {
                    var pw = (from a in db.Accounts
                             where a.username == username
                             select a.password).First();

                    if (pw.Trim() != password)
                    {
                        return Content(new AjaxResult { state = ResultType.error.ToString(), message = "密码错误!" }.ToJson());
                    }
                    else if (Session["ValidateCode"].ToString() != code)
                    {
                        return Content(new AjaxResult { state = ResultType.error.ToString(), message = "验证码错误!" }.ToJson());
                    }
                    else
                    {
                        Session["UserName"] = username;
                        return Content(new AjaxResult { state = ResultType.success.ToString(), message = "登录成功!" }.ToJson());
                    }
                }
            }

            catch (Exception ex)
            {
                return Content(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson());
            }
        }
    }
}
5.添加视图

给LoginController.cs中的index方法添加视图,视图代码如下

@{
    Layout = null;
}





    
    
    用户登录
    
    


    
        

ContosoUniversity登陆验证 用户名 密码 看不清?换一张 点击注册

如上,功能已经完成。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906207.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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