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
{
/// <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(" ", ""));
}
}
}
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方法添加视图,视图代码如下文章来源:https://www.toymoban.com/news/detail-439803.html
@{
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模板网!