您的位置:首页 - 教程 - HoverTreeTop - 正文
ASP.NET使用Login控件实现用户登录
ASP.NET的Login控件,可以方便的在页面上显示用户名和密码输入框和登录按钮。OnAuthenticate事件表示点击登录按钮对输入进行验证。下面给出一个例子,包括登录,判断登录状态,获取登录用户名,退出等功能。源码包含在HoverTreeTop解决方案的ExampleHoverTree项目中,在文后附有下载。Login.aspx页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="ExampleHoverTree.HtExample.Login" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Login登录控件使用实例_何问起</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Login runat="server" ID="login_hovertree" DisplayRememberMe="False" OnAuthenticate="login_hovertree_Authenticate">
</asp:Login>
</div>
</form>
</body>
</html>
Login.aspx.cs
using System;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace ExampleHoverTree.HtExample
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void login_hovertree_Authenticate(object sender, AuthenticateEventArgs e)
{
if (login_hovertree.UserName.Trim().ToLower() == "hewenqi" && login_hovertree.Password == "hovertree")
{
e.Authenticated = true;
FormsAuthentication.SetAuthCookie(login_hovertree.UserName.Trim().ToLower(), false);
}
else
{
e.Authenticated = false;
}
Response.Redirect("loginresult.aspx");
}
}
}
输入用户名hewenqi,密码hovertree,则登录成功。登录成功后跳转到LoginResult.aspx页,在该页显示登录用户名,并有注销登录功能。LoginResult.aspx页:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LoginResult.aspx.cs" Inherits="ExampleHoverTree.HtExample.LoginResult" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>登录结果_何问起</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal runat="server" ID="literal_loginReuslt" />
<br />
<a href="Login.aspx">登录</a>
<asp:LinkButton runat="server" ID="linkButton_logout" Text="退出" OnClick="linkButton_logout_Click" />
</div>
</form>
</body>
</html>
LoginResult.aspx.cs代码:
using System;
using System.Web;
using System.Web.Security;

namespace ExampleHoverTree.HtExample
{
public partial class LoginResult : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Request.IsAuthenticated)
{
literal_loginReuslt.Text = "登录成功,用户名:"+ HttpContext.Current.User.Identity.Name;
}
else
{
literal_loginReuslt.Text = "登录失败";
}
}

protected void linkButton_logout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("login.aspx");
}
}
}
代码下载:http://hovertree.com/h/bjaf/hv6cqe5n.htm

评论: