我试图在ASP中设置登录页面,但即使我输入正确的用户名和密码,我也会收到消息,"您的登录尝试失败了。请再试一次。"我做错了什么?
以下是代码:
ASPX:
if (manners = true)
aspx.cs:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LogIn.aspx.cs" Inherits="MembershipSite.LogIn" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>LogIn Page</h2>
<asp:Label ID="Label1" runat="server" Text="Please log in below to access the membership area."></asp:Label>
<br />
<br />
<asp:Login ID="LoginControl" runat="server"
onauthenticate="LoginControl_Authenticate">
</asp:Login>
</div>
</form>
</body>
</html>
的Web.config:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data.SqlClient;
using HashLibrary;
using System.Configuration;
using System.Text.RegularExpressions;
namespace MembershipSite
{
public partial class LogIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
{
bool authenticated = this.ValidateCredentials(LoginControl.UserName, LoginControl.Password);
if (authenticated)
{
FormsAuthentication.RedirectFromLoginPage(LoginControl.UserName, LoginControl.RememberMeSet);
}
}
public bool IsAlphaNumeric(string text)
{
return Regex.IsMatch(text, "^[a-zA-Z0-9]+$");
}
private bool ValidateCredentials(string userName, string password)
{
bool returnValue = false;
if (this.IsAlphaNumeric(userName) && userName.Length <= 50 && password.Length <= 50)
{
SqlConnection conn = null;
try
{
string sql = "select count(*) from UsersMemb where username = @username and password = @password";
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MembershipSiteConStr"].ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter user = new SqlParameter();
user.ParameterName = "@username";
user.Value = userName.Trim();
cmd.Parameters.Add(user);
SqlParameter pass = new SqlParameter();
pass.ParameterName = "@password";
pass.Value = Hasher.HashString(password.Trim());
cmd.Parameters.Add(pass);
conn.Open();
int count = (int)cmd.ExecuteScalar();
if (count > 0) returnValue = true;
}
catch (Exception ex)
{
// Log your error
}
finally
{
if (conn != null) conn.Close();
}
}
else
{
// Log error - user name not alpha-numeric or
// username or password exceed the length limit!
}
return returnValue;
}
}
}
答案 0 :(得分:0)
另一种方法是使用FormsAuthentication.SetAuthCookie方法并手动将用户重定向到指定的页面。
例如:
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
Response.Redirect('WebForm1.aspx');