第一次做登录功能,有点缺陷,代码比较简单,没有过多介绍。
一、创建一个LoginModel.cs 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace System.Models
{
public class LoginModel
{
[Required(ErrorMessage = "请输入用户名")]
[Display(Name = "用户名")]
public string loginName { get; set; }
[Required(ErrorMessage = "请输入密码")]
[Display(Name = "密码")]
public string pwd { get; set; }
[Required(ErrorMessage = "验证码必须填写")]
[Display(Name = "验证码")]
public string Vcode { get; set; }
}
}
二、界面
ps:因为是用layui做的,所以还需要引入layui 相关的js和样式。
@model System.Models.LoginModel
@{
if (ViewData["IsShowAlert"] != null && ViewData["IsShowAlert"].ToString() == "True")
{
Response.Write(" <script>alert('" + ViewData["alert"] + "'); </script>");
}
}}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录--layui后台管理模板</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
@Styles.Render("~/Content/layuicms/layui/css/layui.css")
@Styles.Render("~/Content/layuicms/css/login.css")
@Styles.Render("~/Scripts/jquery-1.10.2.js")
@Scripts.Render("~/Scripts/jquery.validate.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")
<style type="text/css">
.login {
height:300px !important;
}
</style>
</head>
<body>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div class="video-player" preload="auto" autoplay="autoplay" loop="loop" data-height="1080" data-width="1920" height="1080" width="1920">
<!--背景图片-->
<img src="~/Content/layuicms/page/login/login.jpg" style="width:100%; height:100%"/>
</div>
<div class="login">
<h1>登录</h1>
<form class="layui-form">
<div class="layui-form-item">
@Html.TextBoxFor(m => m.loginName, new { @class = "layui-input", @placeholder= "用户名" })
@Html.ValidationMessageFor(m => m.loginName)
</div>
<div class="layui-form-item">
@Html.PasswordFor(m => m.pwd, new { @class = "layui-input", @placeholder = "密码" })
@Html.ValidationMessageFor(m => m.pwd)
</div>
<div class="layui-form-item form_code">
@Html.TextBoxFor(m => m.Vcode, new { @style = "height: 38px;line - height: 38px;width:126px ", placeholder = "验证码", id = "Vcode" })
<img src="~/Login/GetValidateCode" alt="验证码" id="vcodeimg" style="cursor:pointer;height:36px;width:80px" />
<a href ="javascript:changeCode()" style="text-decoration: underline;"> 换一张</a>
@Html.ValidationMessageFor(m => m.Vcode)
</div>
<input type="submit" value="登录" class="layui-btn login_btn" />
</form>
</div>
}
@Scripts.Render("~/Content/layuicms/layui/layui.js")
@Scripts.Render("~/Content/layuicms/page/login/login.js")
<script type="text/javascript">
function changeCode() {
document.getElementById('vcodeimg').src = document.getElementById('vcodeimg').src + '?';
}
</script>
</body>
</html>
效果图:
login还要用到的js和css
layui.config({
base : "js/"
}).use(['form','layer'],function(){
var form = layui.form(),
layer = parent.layer === undefined ? layui.layer : parent.layer,
$ = layui.jquery;
//video背景
$(window).resize(function () {
if ($(".video-player").width() > $(window).width()) {
$(".video-player").css({ "height": $(window).height(), "width": "auto", "left": -($(".video-player").width() - $(window).width()) / 2 });
} else {
$(".video-player").css({ "width": $(window).width(), "height": "auto", "left": -($(".video-player").width() - $(window).width()) / 2 });
}
}).resize();
登录按钮事件
//form.on("submit(login)", function (data) {
// window.location.href = "/Home";
// return false;
//})
})
//css部分
body{overflow:hidden;}
.video-player{background-color: transparent;min-width: 100%;min-height: 100%;display: block;position: absolute;z-index: 1;top:0;}
.video_mask{ width:100%; height:100%; position:absolute; left:0; top:0; z-index:90; background-color:rgba(0,0,0,0.5); }
.login{ height:260px;width:260px;padding: 20px;background-color:rgba(0,0,0,0.5);border-radius: 4px;position:absolute;left: 50%;top: 50%; margin:-150px 0 0 -150px;z-index:99;}
.login h1{ text-align:center; color:#fff; font-size:24px; margin-bottom:20px; }
.form_code{ position:relative; }
.form_code .code{ position:absolute; right:0; top:1px; cursor:pointer; }
.login_btn{ width:100%; }
控制器部分:
using Common.Tools;
using DefaultConnection;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Models;
using System.Web;
using System.Web.Mvc;
using Moon.Orm;
using BLL;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace WebApplication3.Controllers
{
public class LoginController : Controller
{
[Dependency]
public UserBLL usBLL { get; set; }
// GET: Login
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(LoginModel model)
{
try
{
if (ModelState.IsValid==true)
{
if (Session["ValidateCode"].ToString() != model.Vcode)
{
ViewData["IsShowAlert"] = true;
ViewData["alert"] = "验证码错误";
} else{
var userinfo3 = usBLL.GetByLogin(model.loginName, model.pwd);
if (userinfo3 != null)
{
User ss = new User()
{
Id = userinfo3.Id,
LoginName = userinfo3.LoginName,
PassWord = userinfo3.PassWord,
Name = userinfo3.Name
};
Session["Loginname"] = ss;
return RedirectToAction("", "Home");
}
else
{
ViewData["IsShowAlert"] = true;
ViewData["alert"] = "帐号或者密码错误";
}
}
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
return View();
}
//验证码
public ActionResult GetValidateCode()
{
ValidateCode vCode = new ValidateCode();
string code = vCode.CreateValidateCode(5);
Session["ValidateCode"] = code;
byte[] bytes = vCode.CreateValidateGraphic(code);
return File(bytes, @"image/jpeg");
}
}
}
UserBLL 部分:
/// <summary>
/// 登录用
/// </summary>
/// <param name="loginName"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public User GetByLogin(string loginName, string pwd)
{
User item = null;
var mql = UserSet.SelectAll().Where( UserSet.LoginName.Equal(loginName).And( UserSet.PassWord.Equal(pwd)));
List< User> list = rmsUserRoleDal.GetOwnList< User>(mql);
if (list.Count == 0)
{
return item;
}
return list[0];
}
ValidateCode 类 (在网上找的)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace Common.Tools
{
/// <summary>
/// 生成验证码对象
/// </summary>
public class ValidateCode
{
public ValidateCode()
{
}
///<summary>
/// 验证码的最大长度
///</summary>
public int MaxLength
{
get { return 10; }
}
///<summary>
/// 验证码的最小长度
///</summary>
public int MinLength
{
get { return 1; }
}
///<summary>
/// 生成验证码
///</summary>
///<param name="length">指定验证码的长度</param>
///<returns></returns>
public string CreateValidateCode(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
string validateNumberStr = "";
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
int[] seeks = new int[length];
for (int i = 0; i < length; i++)
{
beginSeek += 10000;
seeks[i] = beginSeek;
}
//生成随机数字
for (int i = 0; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = 1 * (int)Math.Pow(10, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取随机数字
for (int i = 0; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(0, numLength - 1);
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
}
//生成验证码
for (int i = 0; i < length; i++)
{
validateNumberStr += validateNums[i].ToString();
}
return validateNumberStr;
}
///<summary>
/// 创建验证码的图片
///</summary>
///<param name="containsPage">要输出到的page对象</param>
///<param name="validateNum">验证码</param>
public byte[] CreateValidateGraphic(string validateCode)
{
Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 14.0), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.5f, true);
g.DrawString(validateCode, font, brush, 3, 2);
//画图片的前景干扰点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//保存图片数据
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
}
登录成功后Home后台接收后将登陆人的信息显示在界面:
using DefaultConnection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication3.ActionFilter;
namespace WebApplication3.Controllers
{
public class HomeController : Controller
{
[LoginActionFilter]
public ActionResult Index()
{
User user = (User)Session["Loginname"];
User ss = new User()
{
Id = user.Id,
LoginName = user.LoginName,
PassWord = user.PassWord,
Name = user.Name
};
ViewBag.LoginName = ss.Name;
return View();
}
public ActionResult Main() {
return View();
}
public ActionResult LoginError()
{
return View();
}
}
}
LoginActionFilter.css
using DefaultConnection;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Models;
using System.Web;
using System.Web.Mvc;
namespace WebApplication3.ActionFilter
{
public class LoginActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
User userLoginedModel = (User)filterContext.RequestContext.HttpContext.Session["Loginname"];
if (userLoginedModel == null)
{
filterContext.Result = new RedirectResult("/Home/LoginError");
}
return;
}
}
}
效果:
LoginError错误提示界面:
@{
ViewBag.Title = "LoginError";
}
<script type="text/javascript">
window.onload = function () {
document.getElementById("error_content").innerHTML = "在线状态超时或未登录";
setTimeout("toLogin()", 1000);
}
function toLogin() {
top.location.replace('/Login/Index');
}
</script>
<div style="position:absolute;top:50%;left:30%;"><h1 id="error_content"></h1></div>