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

这篇具有很好参考价值的文章主要介绍了.NETMVC5登录页面及验证码功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.成品截图

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

文件结构如图:

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

 

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
    {
        /// <summary>
        /// 操作结果类型
        /// </summary>
        public object state { get; set; }
        /// <summary>
        /// 获取 消息内容
        /// </summary>
        public string message { get; set; }
        /// <summary>
        /// 获取 返回数据
        /// </summary>
        public object data { get; set; }
    }
    /// <summary>
    /// 表示 ajax 操作结果类型的枚举
    /// </summary>
    public enum ResultType
    {
        /// <summary>
        /// 消息结果类型
        /// </summary>
        info,
        /// <summary>
        /// 成功结果类型
        /// </summary>
        success,
        /// <summary>
        /// 警告结果类型
        /// </summary>
        warning,
        /// <summary>
        /// 异常结果类型
        /// </summary>
        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<T>(this string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
        }
        public static List<T> ToList<T>(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
        }
        public static DataTable ToTable(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
        }
        public static JObject ToJObject(this string Json)
        {
            return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
        }
    }
}

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: 50px;*/
	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('<div class="tips_msg"><i class=fa fa-question-circle></i>' + msg + '</div>');
        },

        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;
}

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>用户登录</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
    <link href="~/LocalStyle/CSS/LoginStyle.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <h1 class="login-heading">ContosoUniversity登陆验证</h1>
        <div class="login">
            <div>
                用户名<input type="text" name="username" id="username" placeholder="用户名" class="input-txt" required="" />
            </div>
            <div>
                密码<input type="password" name="password" id="password" placeholder="密码" class="input-txt" required="" />
            </div>

            <div>
                <input type="text" name="name" placeholder="验证码" style="width:190px;" id="validateCode" class="input-txt" />
                <div style="width:210px;float:right;padding-top:14px;padding-left:14px;">
                    看不清?<a id="switchCode" href="javascript:void();" style="text-decoration:none">换一张</a>
                    <img id="imgCode" class="authcode" src="~/Login/GetAuthCode" width="80" height="25" alt="换一个" />
                </div>
            </div>

            <div class="login-footer">
                <a href="#" class="lnk">
                    <span>点击注册</span>
                </a>
                <button id="loginButton" type="button" class="btn btn--right"><span>登录</span></button>
            </div>
            <div class="login_tips" style="color:red;"></div>
        </div>
    </div>

    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script src="~/LocalStyle/Javascript/LoginScript.js"></script>
</body>
</html>

如上,功能已经完成。文章来源地址https://www.toymoban.com/news/detail-439803.html

到了这里,关于.NETMVC5登录页面及验证码功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • IDEA Android用户登录页面、登录验证、页面跳转演示示例全部源码

    开发工具: IDEA 2022.3.2,未连接数据库。验证用的用户名和密码为内置硬编码 演示程序运行效果:     设计器中的用户登录页面布局:  登录验证容错提示如下: 1,用户名不能为空: 2,密码不能为空:     3,用户名不存在: 4,用户密码错误    5,登录验证成功跳转到用户

    2024年02月11日
    浏览(44)
  • 个人博客系统 -- 登录页面添加图片验证码

    目录 1. 功能展示 2. 前段代码 3. 后端代码 在登录页面添加验证码登录 1. 检测到没有输入验证码或者输入的验证码错误时,进行弹窗提示.并且刷新当前验证码图片 2. 点击验证码进行刷新   1. 添加验证码标签,在密码的下面,在login.html进行修改 主要改动如下: 2. 在提交的函数中加

    2024年02月15日
    浏览(51)
  • 使用Edge和chrom扩展工具(GoFullPage)实现整页面截图或生成PDF文件

    插件GoFullPage下载:点击免费下载 如果在浏览网页时,有需要整个页面截图或导出PDF文件的需求,这里分享一个Edge浏览器的扩展插件:GoFullPage。 这个工具可以一键实现页面从上到下滚动并截取。  一、打开“管理扩展”(edge://extensions/),打开获取Microsoft Edge扩展。  二、搜

    2024年02月12日
    浏览(32)
  • 微信小程序登录页验证与页面跳转(二) ---结合SpringBoot和MySQL实现多用户登录

    Spring Boot的开发环境如下: 1、IDEA:2020 2、JDK版本:1.8 3、MySQL 版本:8 代码如下(示例): 打开IDEA,新建项目: 这里选择Spring lnitializr: 在接下来的页面中进行如下配置: 进行下一步:选择SpringBoot的版本,这里选择的是2.7.14 然后: 设置项目所在路径和设置项目名称: 项

    2024年01月22日
    浏览(45)
  • SpringBoot+Vue3实现登录验证码功能

    Redis缓存穿透、击穿、雪崩问题及解决方法 Spring Cache的使用–快速上手篇 分页查询–Java项目实战篇 全局异常处理–Java实战项目篇 Java实现发送邮件(定时自动发送邮件)_java邮件通知_心态还需努力呀的博客-CSDN博客 该系列文章持续更新,更多的文章请点击我的主页查看哦!

    2024年02月01日
    浏览(35)
  • node.js(expree.js )模拟手机验证码功能及登录功能

    dbconfig.js 测试验证码发送 测试登录

    2024年01月19日
    浏览(32)
  • asp.net mvc实现系统登录及验证功能

    在网上购物或者实际的使用过程中经常遇到这样的一个场景:你必须输入用户米/密码,进行登录。登录完成后,界面自动跳转到之前的界面或者主页。具体下面的三个图所示。 在ASP.NET MVC中有个功能是身份认证(就是使用用户名和密码登录的问题),以及使用角色登录的功能

    2024年02月02日
    浏览(30)
  • 【手机号验证/前端】Vue2+elementUI编写一个手机号验证码登录页面,路由式开发(附完整代码)

    目录 效果图: 一、template部分 二、style样式 三、script部分 1.先对手机号的格式进行一个判断 2.接下来就是表单验证规则rules 3.最后就是methods了 (1)首先我们给获取验证码绑定一个方法 (2)然后封装一个axios接口,方便后面测试联调(这部分每个人封装的都不一样) (3)然

    2024年02月17日
    浏览(44)
  • 菜鸟级:Vue Element-UI 前端 + Flask 后端 的登录页面验证码

    这里记录登录页面验证码的做法,采取的是前后端分离的做法,前端用Vue,后端用Flask 首先是GIF效果图: 后端返回的数据结构(base64字符串,response.data.img):   1、Vue前端页面基本采用Ruoyi Ui里面的登录页面代码,里面的一些方法进行重写; 首先是单个vue文件里网页内容

    2023年04月08日
    浏览(51)
  • 如何通过腾讯云短信实现发送验证码并校验验证码以实现登录功能

    验证码相关的10种技术 图像处理技术:生成、识别、验证验证码的图像。 机器学习技术:让计算机自动学习并识别验证码。 文字识别技术:将图像中的文字转换成计算机可读的文本。 模式识别技术:识别验证码中的模式及规律。 图像噪声处理技术:去除图像中的噪声干扰。

    2024年02月10日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包