ASP.NET + jQuery + AJAX 实现用户登录
用户登录在网站中是不可或缺的功能,常见的方法就是使用Form表单将数据提交给后台,后台对帐号密码进行验证从而实现了用户登录。
随着技术的发展,一些网站开始使用 AJAX 的方式进行登录,登录成功后只会刷新局部,从而提升了用户体验。在本文中,将使用ASP.NET和jQuery来实现登录功能。
准备数据库
我们使用SQLServer数据库,创建一章 Users 表,SQL 语句如下:
GO
/****** Object: Table [dbo].[Users] Script Date: 2017/2/9 21:25:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NOT NULL,
[Password] [nvarchar](50) NOT NULL,
[RegTime] [datetime] NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[UserID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
然后往Users表里面插入一条数据:
GO
SET IDENTITY_INSERT [dbo].[Users] ON
INSERT [dbo].[Users] ([UserID], [UserName], [Password], [RegTime]) VALUES (1, N'hexianghui', N'E10ADC3949BA59ABBE56E057F20F883E', CAST(0x0000A715015BDD20 AS DateTime))
SET IDENTITY_INSERT [dbo].[Users] OFF
前端页面
记得在 head 中引入 jQuery 类库。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UserAjaxLoginDemo.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ASP.NET+jQuery+ AJAX 实现用户登录实例</title>
<script src="Js/jquery.min.js"></script>
<style type="text/css">
#loginForm {
border: 1px solid gray;
text-align: center;
width: 300px;
}
#loginForm tr {
height: 35px;
}
#loginForm tr:nth-child(1) {
background-color: skyblue;
font-weight: bold;
}
</style>
</head>
<body>
<table id="loginForm">
<tr>
<td>用户登录</td>
</tr>
<tr>
<td>
<label>用户名:</label><input type="text" name="userName" value=" " />
</td>
</tr>
<tr>
<td>
<label>密 码:</label><input type="password" name="password" value="" />
</td>
</tr>
<tr>
<td>
<input type="button" name="btnSubmit" value="登 录" />
</td>
</tr>
</table>
</body>
</html>
jQuery 代码
用户在点击登录按钮以后,先验证用户名密码是否为空,然后向 UserLogin.ashx 文件发送 AJAX 请求,如果验证成功,则会在登录按钮下显示登录成功,否则提示相应的错误信息。
<script type="text/javascript">
$(function () {
$("input[name='btnSubmit']").click(function () {
var _this = $(this);
var userName = $("input[name='userName']").val().trim();
var password = $("input[name='password']").val().trim();
if (userName == "") {
alert("用户名不能为空!");
$("input[name='userName']").focus();
return false;
}
if (password == "") {
alert("密码不能为空!");
$("input[name='password']").focus();
return false;
}
$.ajax({
type: "POST",
url: "UserLogin.ashx",
dataType: "JSON",
data: { "userName": userName, "password": password },
beforeSend: function () {
_this.val("登录中...");
},
success: function (result) {
if (result.statusCode == 200) {
var trObj = "<tr><td><span style='color:green;'>登录成功!</span>欢迎您:" + result.username + "</td></tr>";
$(trObj).appendTo("#loginForm");
} else {
alert(result.message);
}
}
});
_this.val("登 录");
});
});
</script>
UserLogin.ashx 文件
先判断请求方法是不是POST,然后接收传过来的用户名和密码,并使用 DBHelper 类与数据库中的用户名和密码进行比对,如果比对成功,则使用FormsAuthenticationTicket 创建身份验证票据,并返回用户名和状态码,否则返回对应的错误信息。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Security.Cryptography;
using System.Web.Security;
using System.Text;
namespace UserAjaxLoginDemo
{
/// <summary>
/// UserLogin 的摘要说明
/// </summary>
public class UserLogin : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/json";
if (context.Request.HttpMethod.ToUpper().Equals("POST"))
{
string userName = context.Server.HtmlEncode(context.Request.Form["userName"]);
string password = context.Server.HtmlEncode(context.Request.Form["password"]);
if (userName.Trim().Equals(""))
{
this.ResponseJsonMsg(201, "用户名不能为空!");
}
if (password.Trim().Equals(""))
{
this.ResponseJsonMsg(201, "密码不能为空!");
}
password = this.Str2Md5(password);
string sql = string.Format("SELECT * FROM Users WHERE UserName = '{0}'", userName);
DataTable dt = DBHelper.GetInstance().GetDataTable(sql);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Password"].ToString().Equals(password))
{
//创建身份验证票据
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userName,
DateTime.Now,
DateTime.Now.AddDays(30),
true,
"User",
FormsAuthentication.FormsCookiePath);
//加密身份验证票据
string hash = FormsAuthentication.Encrypt(ticket);
//创建要发送到客户端的cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.Expires = ticket.Expiration;
context.Response.SetCookie(cookie);
var obj = new
{
statusCode = 200,
username = userName,
message = "登录成功!"
};
context.Response.Write(new JavaScriptSerializer().Serialize(obj));
}
else
{
this.ResponseJsonMsg(202, "密码错误!");
}
}
else
{
this.ResponseJsonMsg(202, "用户不存在!");
}
}
}
/// <summary>
/// 响应json消息
/// </summary>
/// <param name="code"></param>
/// <param name="msg"></param>
public void ResponseJsonMsg(int code, string msg)
{
var obj = new
{
statusCode = code,
message = msg
};
HttpContext.Current.Response.Write(new JavaScriptSerializer().Serialize(obj));
HttpContext.Current.Response.End();
}
/// <summary>
/// 字符串MD5加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string Str2Md5(string str)
{
byte[] result = Encoding.Default.GetBytes(str.Trim());
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
return BitConverter.ToString(output).Replace("-", "");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
总结
总的来说,登录的流程为 AJAX 提交数据 =》后台验证数据并返回相应的消息 =》根据返回的消息进行操作。
这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。