简体   繁体   English

输入正确的用户名和密码后,ASP登录无法正常工作

[英]ASP login doesn't work when correct username and password are entered

I'm trying to set up a login page in ASP, but even when I enter the correct username and password, I get the message, "Your login attempt was not successful. Please try again." 我试图在ASP中设置登录页面,但是即使输入正确的用户名和密码,也会收到消息“您的登录尝试失败。请重试。” What am I doing wrong? 我究竟做错了什么?

Here is the code: 这是代码:

aspx: aspx:

<%@ 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>

aspx.cs: aspx.cs:

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;
        }

    }
}

Web.config: Web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>


  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.6.1"/>
    <httpRuntime targetFramework="4.6.1"/>

    <authentication mode="Forms">
      <forms defaultUrl="~/members/member.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="20"></forms>
    </authentication>

  </system.web>


  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>


  <connectionStrings>
    <add name="MembershipSiteConStr" connectionString="Data Source=TIMLAWLOR-HP\SQLEXPRESS; database=DmiVideoApp; Persist Security Info=True; integrated security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>


</configuration>

Another approach is using FormsAuthentication.SetAuthCookie method and manually redirect user to specified page. 另一种方法是使用FormsAuthentication.SetAuthCookie方法,并将用户手动重定向到指定页面。

For example: 例如:

 FormsAuthentication.SetAuthCookie(txtUserName.Text, false);

   Response.Redirect('WebForm1.aspx');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 由于用户不存在/密码/用户名正确而导致尝试登录网站失败时如何返回消息? - How to return a message when a try to login to the website failed, because the user does not exist/password/username arent correct? 尝试创建登录页面,但用户名与密码不匹配 [学习目的] - Trying to create a login page but it doesn't match username against password [Learning purpose] ASP.NET MVC和身份 - 重置密码不起作用 - ASP.NET MVC and Identity - Reset password doesn't work 我的登录始终成功,无论用户名或密码正确/错误 - my login is always successful, whether it is correct/wrong username or password 在登录表单上输入用户名和密码后,处理登录表单并显示主表单 - Dispose login form and show main form after username and password are entered on login form 登录不起作用 - Login doesn't work POST asp.net表单用户名和密码以外部HTTPS登录 - POST asp.net form username and password to an external HTTPS login DeploymentItemAttribute不起作用(正确) - DeploymentItemAttribute doesn't work (correct) 为什么我的登录表单允许用户使用正确的用户名登录,但密码不正确? - Why my login form allowing users to login with correct USERNAME, but incorrect PASSWORD? 检查可用的用户名不起作用 - Checking Username Available Doesn't Work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM