ASP.NET中使用Entity Framework开发登陆注册Demo
这里更多的是当作随身笔记使用,记录一下学到的知识,以便淡忘的时候能快速回顾
当前步骤是该项目的第一部分
直接上步骤,有类似的开发登陆注册也可以参考。
登陆注册的话,肯定要用到的就是Users表的注册和登录
先演示一下怎么通过数据库添加EF
如果已经完成EF添加数据库,点击跳到下一步
右键新建项,找到ADO.NET实体数据模型,点击下一步
选择第一个,来自数据库的EF设计器,
(如果想通过代码,构建数据库的话,选择第三个Code First模型)
先新建连接,在选择下一步
选好数据库选好服务器
选择你需要的表,点击完成
已完成EF添加数据库
构建一个BLL层,主要是注册和登录有关数据库的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using WebApplication1.DAL;
namespace WebApplication1.BLL
{
public class UserService
{
//注册代码
public static bool register(string Id, string Pwd, string name, string phone)
{
Pwd = PasswordEncryption(Pwd);
using (OLMSDBEntities db = new OLMSDBEntities())
{
Users users = db.Users.Add(new Users
{
LoginId = Id,
LoginPwd = Pwd,
UserName = name,
RoleId = 2,
Phone = phone,
DateCreated = DateTime.Now,
UserStatus = 1
});
if (db.SaveChanges() > 0)
{
return true;
}
return false;
}
}
//登录代码
public static Users Login(string loginId, string loginPwd)
{
loginPwd = PasswordEncryption(loginPwd);
using (OLMSDBEntities db = new OLMSDBEntities())
{
Users users = db.Users.FirstOrDefault(u => u.LoginId == loginId
&& u.LoginPwd == loginPwd);
return users;
}
}
private static string PasswordEncryption(string pwd)
{ //创建SHA1加密算法对象
SHA1 sha1 = SHA1.Create(); //将原始密码转换为字节数组
byte[] originalPwd = Encoding.UTF8.GetBytes(pwd); //执行加密
byte[] encryPwd = sha1.ComputeHash(originalPwd); //将加密后的字节数组转换为大写字符串
return string.Join("", encryPwd.Select(b => string.Format("{0:x2}", b)).ToArray()).ToUpper();
}
}
}
这里附上验证码的页面, 不需要的自行跳过
右键添加新建项,选择一般处理程序,点击完成即可
下面时handler的代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace WebApplication1
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
//选取的颜色
Color[] colors = { Color.White };
//通过Bitmap构造Image
Image img = new Bitmap(100, 60);
//Graphics绘画Image
Graphics graphics = Graphics.FromImage(img);
Random random = new Random(DateTime.Now.Millisecond);
//验证码的四位数
int charNum1 = random.Next('0', '9' + 1);
int charNum2 = random.Next('0', '9' + 1);
int charNum3 = random.Next('0', '9' + 1);
int charNum4 = random.Next('0', '9' + 1);
//把生成的随机数变成字符串,通过char进行转换
string validCode = string.Format($"{(char)charNum1}{(char)charNum2}{(char)charNum3}{(char)charNum4}");
//放进Session进行存储,记得继承接口,否则疯狂报空指针
context.Session["verification_Code"] = validCode;
//字体的大小和类别
Font font = new Font("宋体", 24);
//随机的颜色
Brush brush1 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
//DrawString的四个参数,第一个是要写的字符,第二个是字体,第三个是颜色,第四个是坐标x,y
graphics.DrawString(((char)charNum1).ToString(), font, brush1, 7, -3);
Brush brush2 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum2).ToString(), font, brush2, 26, -9);
Brush brush3 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum3).ToString(), font, brush3, 50, 0);
Brush brush4 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum4).ToString(), font, brush4, 70, -7);
//保存,格式
context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
//释放资源
graphics.Dispose();
img.Dispose();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
验证码的handler已完成
然后就是一个登录的页面Login.aspx
这里添加的css就不给予了,页面可自行调
我这里有一个验证码的图片,如果没做上面的验证码,请自行把验证码跳过
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebApplication1.Login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="Assets/css/login.css" rel="stylesheet" />
<link href="Assets/css/animate.min.css" rel="stylesheet" />
<link href="Assets/css/font-awesome.min.css" rel="stylesheet" />
<link href="Assets/css/grids-responsive-min.css" rel="stylesheet" />
<link href="Assets/css/input.css" rel="stylesheet" />
<link href="Assets/css/main.css" rel="stylesheet" />
<link href="Assets/css/pure-min.css" rel="stylesheet" />
<link href="Assets/css/shop.css" rel="stylesheet" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div class="login-container pure-g">
<div class="pure-u-md-3-4">
</div>
<div class="pure-u-md-1-4">
<h4>在线音乐商店</h4>
<asp:Panel ID="login" runat="server">
<div class="pure-u-1 pure-u-md-2-3">
登录账号
<br />
<asp:TextBox ID="login_id" runat="server"></asp:TextBox>
</div>
<div class="pure-u-1 pure-u-md-2-3">
登录密码
<br />
<asp:TextBox ID="login_pwd" TextMode="Password" runat="server"></asp:TextBox>
</div>
<div class="pure-u-1 pure-u-md-2-3">
验证码
<br />
<asp:TextBox ID="login_Code" runat="server"></asp:TextBox>
</div>
<%--验证码的地方,一定要注意路径--%>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Handler1.ashx" onclick="this.src=this.src+1" Width="100" Height="40"/>
</asp:Panel>
<%--注册--%>
<asp:Panel ID="rex" runat="server" CssClass="">
<div class="pure-u-1 pure-u-md-2-3">
登录账号
<br />
<asp:TextBox ID="reg_id" runat="server"></asp:TextBox>
</div>
<div class="pure-u-1 pure-u-md-2-3">
登录密码
<br /><asp:TextBox ID="reg_pwd" runat="server" TextMode="Password"></asp:TextBox>
</div>
<div class="pure-u-1 pure-u-md-2-3">
确认密码
<br />
<asp:TextBox ID="reg_pwd2" runat="server" TextMode="Password"></asp:TextBox>
</div>
<div class="pure-u-1 pure-u-md-2-3">
用户姓名
<br />
<asp:TextBox ID="reg_Name" runat="server"></asp:TextBox>
</div>
<div class="pure-u-1 pure-u-md-2-3">
联系电话
<br />
<asp:TextBox ID="reg_Phone" runat="server" TextMode="Phone"></asp:TextBox>
</div>
</asp:Panel>
<div>
<asp:Button ID="btnLogin" CssClass="pure-button button-default pure-button-primary" runat="server" Text="登录" OnClick="btnLogin_Click" />
<asp:Button ID="btnReg" CssClass="pure-button button-default " runat="server" Text="注册" OnClick="btnReg_Click" />
</div>
</div>
</div>
</form>
</body>
</html>
页面的后台代码,我页面用了panel,所有要分开显示,
两个panel的名称叫login和rex
//这里的管理员页面和用户页面我就不做了,可以自己根据需要做一下,注意路径啊
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication1.BLL;
using WebApplication1.DAL;
namespace WebApplication1
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
login.Visible = true;
rex.Visible = false;
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
if (login.Visible)
{
string loginId = login_id.Text;
string loginPwd = login_pwd.Text;
string loginCode = login_Code.Text;
//这里是我验证码存入的时候的verification_Code,取出的时候需要用存入时的单词
string snCode = Session["verification_Code"] as String;
//先判断是不是验证码相同
if (loginCode == snCode)
{
//这里时BLL的登录代码
Users users = UserService.Login(loginId, loginPwd);
if (users != null)
{
//看看是不是管理员,管理员的RoleId为1
//这两个页面我就不做了,自己做,稍微区分一下,主要是管理员和用户登录的不是一个页面
Session["user"] = users;
if (users.RoleId == 1)
{
Response.Redirect("~/Admin/Orders.aspx");
} else
{
Response.Redirect("~/User/WebForm1.aspx");
}
}
else
{
Response.Write("<script language='javascript'>");
Response.Write("alert('错误提示,账号或密码错误。单击“确定”返回网站。');");
Response.Write("</script>");
}
}
} else
{
login.Visible = true;
rex.Visible = false;
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
if (rex.Visible)
{
string id = reg_id.Text;
string pwd = reg_pwd.Text;
string name = reg_Name.Text;
string phone = reg_Phone.Text;
bool bools = UserService.register(id, pwd, name, phone);
if (bools)
{
//这里用js是因为,Response的Redirect会覆盖掉Write的方法
string strUrl = "<script>alert('添加成功');window.location.href='Login.aspx'</script>";
Response.Write(strUrl);
//Response.Write("<script language='javascript'>");
//Response.Write("alert('添加成功');");
//Response.Write("</script>");
//Response.Redirect("Login.aspx");
}
else
{
Response.Write("<script language='javascript'>");
Response.Write("alert('添加失败');");
Response.Write("</script>");
}
}
else
{
login.Visible = false;
rex.Visible = true;
}
}
}
}
效果图:
注册
点击注册,自动跳转到登录
点击登录