asp.net 实现用户登录和注册——基于webform模式

2023-11-14

最近在写asp课程设计,网站登录注册的功能怎么能少,捣鼓了两天终于弄出点东西来了。

    环境:Windows10 + VS2015 + 自带LocalDB

    看一下效果:

    1、注册页面:

如果用户重名:

 

2、登录页:

3、注册或者登录好了会跳到Home页面并且显示当前的用户

下面看看关键代码:

①注册前台页面Register.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="Album.OnlineAlbum.Register" %>
 
<!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>注册</title>
    <style>
        	form{
  
   
    color:#575454;  
    width:500px;
    margin:20px auto;
    font-size:15px;
	}
.label{
    color:red;
    font-size:12px;
    font-family:'Lucida Console';
}
       
input.Tb{
    border-radius:5px;
 
}
 
     .user_name{ width:240px; height:38px; line-height:38px; border:1px solid #000; background:url(login_img_03.png)  no-repeat left center; padding-left:30px; }  
.user_name input{ width:230px; height:36px; border:1px solid #fff;color:#666;}  
.password{ width:240px; height:38px; line-height:38px; border:1px solid #dfe1e8; background:url(login_img_09.png)  no-repeat left center; padding-left:30px; }  
.password input{ width:230px; height:36px; border:1px solid #000;color:#666;}  
.transButton {
    border:solid 1px;
    background-color:transparent;
}
#btnRegister{
  
    font-size:14px;
}
#linkToLogin{
    text-decoration:none
}
#ckItem{
    text-decoration:none
}
body{
       background-image:url("rbg.jpg");
}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    
                <h2>欢迎注册OA</h2>
      
                <h3>每一天,记录美。</h3>
       
                
       
                <br />
 
       <asp:ScriptManager ID="ScriptManager1" runat="server">
               </asp:ScriptManager> 
       
     
           <asp:TextBox runat="server" ID="rUserNameText"   Height="40px" Width="490px" CssClass="Tb"></asp:TextBox>
 
               <br />  
           <asp:UpdatePanel ID="UpdatePanel1" runat="server">
             <ContentTemplate>
                  <asp:CustomValidator ID="CustomValidator1" runat="server" 
    ControlToValidate="rUserNameText" ErrorMessage="*" 
    onservervalidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
             </ContentTemplate>
           
             </asp:UpdatePanel>
                <br />
            <asp:TextBox runat="server" ID="rPsdText"  TextMode="Password" Height="40px" Width="490px" CssClass="Tb"></asp:TextBox>
            <br /> 
         <asp:UpdatePanel ID="UpdatePanel2" runat="server">
             <ContentTemplate>
 <asp:CustomValidator ID="CustomValidator2" runat="server" 
    ControlToValidate="rPsdText" ErrorMessage="*" 
    onservervalidate="CustomValidator2_ServerValidate">
</asp:CustomValidator>
             </ContentTemplate>
           
             </asp:UpdatePanel>
            <br />
           <asp:TextBox runat="server" ID="rrPsdText"  TextMode="Password" Height="40px" Width="490px" CssClass="Tb" ></asp:TextBox>
           <br />
      <asp:UpdatePanel ID="UpdatePanel3" runat="server">
             <ContentTemplate>
       <asp:CustomValidator ID="CustomValidator3" runat="server" 
    ControlToValidate="rrPsdText" ErrorMessage="*" 
    onservervalidate="CustomValidator3_ServerValidate">
</asp:CustomValidator>
             </ContentTemplate>
           
             </asp:UpdatePanel>
           
         <br />
         <table>
            <tr>
                <td>
                    <asp:CheckBox ID="CheckBox1" runat="server" Checked="true" />
                </td>
                <td>
                     <span>同意</span>  <asp:LinkButton runat="server" Text="服务条款" ID="ckItem"></asp:LinkButton>
                </td>
                <td>
                                           
                                           
                           
                </td>
                <td>
                  
                    <asp:LinkButton ID="linkToLogin" runat="server" Text="已有账号?登录" OnClick="linkToLogin_Click"></asp:LinkButton>
                </td>
            </tr>
        </table>
        
           
      
 
       
 
        <asp:Button ID="btnRegister" runat="server" CssClass="transButton" Height="49px" Text="注    册" Width="500px" OnClick="btnRegister_Click" />
                 
    
    </form>
    </body>
        <script type="text/javascript">  
        function watermark(id, value) {  
            var obj = document.getElementById(id);
            var isPsdMode = false;
            if (obj.type == "password")
            {
                obj.type = "text";
                isPsdMode = true;
            }
            obj.value = value;  
            obj.style.color = "Gray";
            //获取焦点事件  
            obj.onfocus = function () {
                
                obj.style.color = "Black";
                if (isPsdMode)
                {
                    obj.type = "password";
                }
                if (this.value == value) {  
                    this.value = '';  
                }  
            };  
            //失去焦点事件  
            obj.onblur = function () {  
                if (this.value == "") {
                    if (isPsdMode) {
                        obj.type = "text";
                    }
                    this.value = value;  
                    obj.style.color = "Gray";
                }  
                else {  
                    obj.style.color = "Black";
                }  
            };  
        }  
        window.onload = function () {  
            var arr = [{ 'id': 'rUserNameText', 'desc': '用户名' }, { 'id': 'rPsdText', 'desc': '密码' },{ 'id': 'rrPsdText', 'desc': '确认密码' }];
            for (var i = 0; i < arr.length; i++) {  
                watermark(arr[i].id, arr[i].desc);  
            }  
        };  
    </script> 
</html>

注册后台页面Register.aspx.cs:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
 
namespace Album.OnlineAlbum
{
    public partial class Register : System.Web.UI.Page
    {
        private bool UserNameIselgal = false;
        private bool PsdIselgal = false;
        private bool CanRegister = false;
 
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
 
 
        protected void linkToLogin_Click(object sender, EventArgs e)
        {
            Response.Redirect("Login.aspx");
        }
 
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            Session["User"] = rUserNameText.Text;
            Session["Psd"] = rPsdText.Text;
 
            string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
            SqlConnection conn = new SqlConnection(connStr);
 
          
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("select count(*) from UserTable where UId=@UId", conn);
                cmd.Parameters.Add("@UId", SqlDbType.Char);
                cmd.Parameters[0].Value = Session["User"];
                int count = (int)cmd.ExecuteScalar();
 
                if (count > 0)
                {
 
                    Response.Write("<script>alert('用户名已存在!')</script>");
                }
                else
                {
                   
                    CanRegister = true;
                }
            }
            catch
            {
                Response.Write("检测重名异常");
            }
 
            finally
            {
                conn.Close();
            }
 
            if (CanRegister)
            {
                try
                {
                    conn.Open();
                    string strIns = "insert into  UserTable(UId, Psd) values(@UId, @Psd)";
                    SqlCommand cmd = new SqlCommand(strIns, conn);
                    cmd.Parameters.Add("@UId", SqlDbType.NChar);
                    cmd.Parameters.Add("@Psd", SqlDbType.NChar);
 
                    cmd.Parameters["@UId"].Value = Session["User"];
                    cmd.Parameters["@Psd"].Value = Session["Psd"];
 
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    Response.Write("注册异常");
                }
                finally
                {
                    conn.Close();
 
                }
            }
            CanRegister = CanRegister && UserNameIselgal && PsdIselgal;
            if (CanRegister)
            {
                Session["CurrentUser"] = rUserNameText.Text;
                Response.Redirect("Home.aspx");
            }
          
        }
 
        protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
        {
            if (rUserNameText.Text.Equals("用户名"))
            {
                CustomValidator1.ErrorMessage = "*用户名为空";
                args.IsValid = false;
            } else if (System.Text.RegularExpressions.Regex.IsMatch(rUserNameText.Text, "^[0-9a-zA-Z]+$") &&
                    rUserNameText.Text.Length > 5 && rUserNameText.Text.Length < 11)
                    {
                    args.IsValid = true;
                    UserNameIselgal = true;
                    }
                 else
                {
                CustomValidator1.ErrorMessage = "*用户名由6~10位数字和字母构成";
                args.IsValid = false;
                 }
 
          
        }
 
        protected void CustomValidator2_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
        {
            if (rPsdText.Text.Equals("密码"))
            {
                CustomValidator2.ErrorMessage = "*密码为空";
                args.IsValid = false;
            }
 
            else if (System.Text.RegularExpressions.Regex.IsMatch(rPsdText.Text, "^[0-9a-zA-Z]+$") &&
              rPsdText.Text.Length > 4)
           {
                args.IsValid = true;
            }
            else
            {
                CustomValidator2.ErrorMessage = "*密码由全数字和字母构成且不少于5位";
                args.IsValid = false;
            }
        }
 
        protected void CustomValidator3_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
        {
            if (rrPsdText.Text.Equals("") ||rrPsdText.Text.Equals("确认密码"))
            {
                args.IsValid = false;
                CustomValidator3.ErrorMessage = "*确认密码为空";
            }
            else if (!rrPsdText.Text.Equals(rPsdText.Text))
            {
                args.IsValid = false;
                CustomValidator3.ErrorMessage = "*两次密码不一致";
            }
            else
            {
                PsdIselgal = true;
                args.IsValid = true;
            }
        }
    }
}

②登录前台页面Login.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Album.OnlineAlbum.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"/>
    <title>登陆</title>
     <style>
        	form{
  
   
    color:#575454;  
    width:500px;
    margin: auto;
    font-size:15px;
    margin-top:260px;
	}
   #spanpsd{
       margin-left:125px;
   }
   #spanuser{
       margin-left:110px;
   }
   div{
       margin:30px auto;
       align-content:center;
   } 
   .textbox{
       border:solid 1px;
       background:rgba(0, 0, 0, 0);
   }
   #LinkButton1{
       text-decoration:none;
       color:lightblue;
        margin-left:230px;
       
   }
   #Button1{
       border-radius:2px;
       border:solid 1px;
    background-color:transparent;
    margin-left:150px;
     margin-top:10px;
   }
  body{
            background-image: url("lbg.jpg");
        }
  
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div>
                <span id="spanuser">用户名:</span>
                <asp:TextBox ID="TextBox1" runat="server" CssClass="textbox" Height="30px" Width="240px"></asp:TextBox>
            </div>
 
            <div>
                <span id="spanpsd">密码:</span>
                <asp:TextBox ID="TextBox2" runat="server" CssClass="textbox" Height="30px" Width="240px" TextMode="Password"></asp:TextBox>
            </div>
 
            <div>
                <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">没有账号?注册</asp:LinkButton>
                <br />
                <asp:Button ID="Button1" runat="server" Text="登 录" Width="270px" Height="40px" OnClick="Button1_Click" />
            </div>
        </div>
           
    </form>
</body>
</html>

登录后台页面Login.aspx.cs:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace Album.OnlineAlbum
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
 
       
 
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
            SqlConnection conn = new SqlConnection(connStr);
 
            try
            {
 
 
                conn.Open();
                SqlCommand cmd = new SqlCommand("select count(*) from UserTable where UId=@UId and Psd=@Psd", conn);
                cmd.Parameters.Add("@UId", SqlDbType.Char);
                cmd.Parameters.Add("@Psd", SqlDbType.Char);
                cmd.Parameters[0].Value = TextBox1.Text;
                cmd.Parameters[1].Value = TextBox2.Text;
                int count = (int)cmd.ExecuteScalar();
                if (count == 1)
                {
 
                    Session["CurrentUser"] = TextBox1.Text;
                    Response.Redirect("./Home.aspx");
 
 
                }
                else
                {
                    Response.Write("<script>alert('用户名或密码错误')</script>");
                }
            }
            catch
            {
                Response.Write("<script>alert('登录异常')</script>");
            }
 
            finally
            {
                conn.Close();
            }
 
        }
    }
}

③Home.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="Album.OnlineAlbum.Home" %>
 
<!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>Online Ablum</title>
    <style>
        #page_header{
           height:20px;
           margin-left:10px;
        }
    </style>
</head>
<body>
   
    
 
        <form runat="server">
           
          
             <asp:LinkButton runat="server" OnClick="Unnamed2_Click" ID="btnToReg">注册</asp:LinkButton>
          
         <asp:LinkButton runat="server" OnClick="Unnamed1_Click" ID="btnToLog">登录</asp:LinkButton>
          
        </form>
         
   
 </body>
</html>

home.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace Album.OnlineAlbum
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurrentUser"] != null)
                btnToReg.Text = Session["CurrentUser"].ToString();
        }
 
        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Login.aspx");
        }
 
        protected void Unnamed2_Click(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }
    }
}    

 Web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
 
  
<connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </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=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
    </modules>
  </system.webServer>
</configuration>

附上项目代码,需要积分下载。

 ps:这是我一个在线相册系统的一部分,完整项目源码见github,可以不用积分下载,不过你得理清我写的东西。

https://blog.csdn.net/richard1997/article/details/79354090

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

asp.net 实现用户登录和注册——基于webform模式 的相关文章

  • requestValidationMode 2.0 和 4.0 有什么区别

    这是 MSDN 的定义 4 0 默认值 HttpRequest 对象在内部设置一个标志 指示每当访问任何 HTTP 请求数据时都应触发请求验证 这保证了在请求期间访问 cookie 和 URL 等数据之前触发请求验证 配置文件中的页面元素
  • 使用 jQuery 将参数从一个 ASP.NET 页面传递到另一页面

    我需要使用 jQuery 将 4 个参数 3 个字符串和一个逗号分隔列表 从 ASP NET 页面传递到另一个 ASP NET 页面 目标页面应该作为单独的窗口启动 这与以下 jQuery 片段配合良好 sourcePageBtn clic
  • 使用 ELMAH 记录 WCF 服务的异常

    我们正在使用优秀的ELMAH http code google com p elmah处理 ASP NET 3 5 Web 应用程序中未处理的异常 这对于除使用 REST 功能使用的 WCF 服务之外的所有站点都非常有效 当操作方法中发生应
  • Nhibernate:连接表并从其他表获取单列

    我有以下表格 create table Users Id uniqueidentifier primary key InfoId uniqueidentifier not null unique Password nvarchar 255
  • 如何在新窗口中打开图像或pdf文件?

    我有一个 gridview 它包含文件名和文件路径 图像和 pdf 格式文件 其中我使用了模板字段 在该字段下放置了 1 个图像按钮 单击该图像按钮 即 查看 按钮 时 我想在新窗口中打开所选文件 这是我的代码 protected void
  • OWIN 可以替代 ASP.NET MVC 应用程序中的 DI 吗?

    大约一年前 在 Visual Studio 中创建时自动生成的 MVC 项目不包含任何有关 OWIN 的内容 作为再次申请并试图了解这些变化的人 我想知道 OWIN 是否可以替代我的 DI 据我了解 Startup Auth cs 中的以下
  • IIS7 上的 ASP.NET 应用程序 - iisreset 后启动速度非常慢

    我有一个在 Windows 2008 上的 IIS7 下运行的 ASP NET 3 5 网站 当我重新启动 IIS iisreset 然后点击一个页面时 初始启动非常慢 我在 Process Explorer 中看到以下活动 w3wp ex
  • CSS、Javascript 和图像的长度为零

    我正在尝试将 ASP NET MVC 1 0 Visual Studio 2008 项目移植到 ASP NET MVC RC 2 Visual Studio 2010 该项目 并且一直 在 IIS 7 上运行 动态内容 由控制器提供的所有内
  • 如何在c#中生成8字节GUID值? [复制]

    这个问题在这里已经有答案了 可能的重复 如何从 GUID 生成 8 字节唯一 ID https stackoverflow com questions 5678177 how to generate 8 bytes unique id fr
  • 管理调试和发布连接字符串

    在 NET SQLServer 应用程序中管理调试和发布连接字符串的好方法是什么 我有两个 SQL Server 一个是生产服务器 一个是构建 调试服务器 我需要一种在部署 ASP NET 应用程序时在这两个服务器之间进行切换的方法 目前
  • Guid 应包含 32 位数字和 4 个破折号

    我有一个包含 createuserwizard 控件的网站 创建帐户后 验证电子邮件及其验证 URL 将发送到用户的电子邮件地址 但是 当我进行测试运行时 单击电子邮件中的 URL 时 会出现以下错误 Guid should contain
  • 使用 json 向 RESTful WCF 发送 Post 请求

    我已经尝试了每种组合来发送请求 以从 jQuery 向 RESTful WCF 发送 POST 请求 有人可以模仿并使其发挥作用吗 代码在这里 http pastebin com Ua97919C http pastebin com Ua9
  • 在 gridview 控件中使用单选按钮

    我有一个 gridview 控件 其中使用存储过程显示数据 该网格有三列 第一列包含单选按钮 总体思路是用户应该能够从 在我的例子中 5 个单选按钮中仅选择一个单选按钮 当前功能的问题是我可以同时选择所有单选按钮 我尝试使用 groupna
  • 当从属文本框中没有输入文本时,如何让 gridview 显示所有表格行?

    下面的代码可以正常工作 并根据文本框中输入的文本过滤我的网格视图 当我的文本框中没有输入任何文本时 我没有得到任何结果 并且无法理解为什么 我的问题 如何让gridview显示all当文本框中没有输入文本时表行 MSSQL Search n
  • 名称在当前上下文中不存在

    所以 我正在我的笔记本电脑和台式机之间完成这个项目 该项目在笔记本电脑上运行 但现在将更新的源代码复制到桌面上后 我的项目中有超过 500 个错误 所有这些错误都是 该名称在当前上下文中不存在 这是一个例子 职位 aspx
  • 获取GridView中选定行的索引

    我想使用复选框获取从 gridview 选择的行 复选框是这样的
  • 将 Windows 窗体应用程序转换为 Asp.net

    我问的是 您之前使用的将 C Windows 窗体应用程序转换为 ASP NET 的最佳工具是什么 我已经关于这个主题 发现了很多工具 但我希望有人根据他的使用情况推荐最好的工具 我真的不建议使用工具来进行转换 Web 应用程序和 WinF
  • 实体框架 4 DB 优先依赖注入?

    我更喜欢创建自己的数据库 设置索引 唯一约束等 使用 edmx 实体框架设计器 从数据库生成域模型是轻而易举的事 现在我有兴趣使用依赖注入来设置一些存储库 我查看了 StackOverflow 上的一些文章和帖子 似乎重点关注代码优先方法
  • 恢复上传文件控制

    我确实阅读了以下帖子 C 暂停 恢复上传 https stackoverflow com questions 1048330 pause resume upload in c 使用 HTTP 恢复上传 https stackoverflow
  • PostgreSQL 错误 42501:架构权限被拒绝

    我正在 ASP NET 中构建一个用户注册系统 使用 PostgreSQL 数据库来维护用户信息 作为注册过程的一部分 用户会收到一条确认消息 他们必须单击其中的链接来验证其电子邮件地址 然后 他们将进入一个可以创建密码的页面 一旦用户提供

随机推荐