找回密码
 会员注册
查看: 124|回复: 0

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

[复制链接]

250

主题

1

回帖

819

积分

管理员

积分
819
发表于 2024-2-29 08:46:29 | 显示全部楼层 |阅读模式

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

    环境:Windows10 + VS2015 + 自带LocalDB

    看一下效果:

    1、注册页面:

如果用户重名:

 

2、登录页:

 

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

 

下面看看关键代码:

①注册前台页面Register.aspx:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="Album.OnlineAlbum.Register" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  6. <title>注册</title>
  7. <style>
  8. form{
  9. color:#575454;
  10. width:500px;
  11. margin:20px auto;
  12. font-size:15px;
  13. }
  14. .label{
  15. color:red;
  16. font-size:12px;
  17. font-family:'Lucida Console';
  18. }
  19. input.Tb{
  20. border-radius:5px;
  21. }
  22. .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; }
  23. .user_name input{ width:230px; height:36px; border:1px solid #fff;color:#666;}
  24. .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; }
  25. .password input{ width:230px; height:36px; border:1px solid #000;color:#666;}
  26. .transButton {
  27. border:solid 1px;
  28. background-color:transparent;
  29. }
  30. #btnRegister{
  31. font-size:14px;
  32. }
  33. #linkToLogin{
  34. text-decoration:none
  35. }
  36. #ckItem{
  37. text-decoration:none
  38. }
  39. body{
  40. background-image:url("rbg.jpg");
  41. }
  42. </style>
  43. </head>
  44. <body>
  45. <form id="form1" runat="server">
  46. <h2>欢迎注册OA</h2>
  47. <h3>每一天,记录美。</h3>
  48. <br />
  49. <asp:ScriptManager ID="ScriptManager1" runat="server">
  50. </asp:ScriptManager>
  51. <asp:TextBox runat="server" ID="rUserNameText" Height="40px" Width="490px" CssClass="Tb"></asp:TextBox>
  52. <br />
  53. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  54. <ContentTemplate>
  55. <asp:CustomValidator ID="CustomValidator1" runat="server"
  56. ControlToValidate="rUserNameText" ErrorMessage="*"
  57. onservervalidate="CustomValidator1_ServerValidate">
  58. </asp:CustomValidator>
  59. </ContentTemplate>
  60. </asp:UpdatePanel>
  61. <br />
  62. <asp:TextBox runat="server" ID="rPsdText" TextMode="Password" Height="40px" Width="490px" CssClass="Tb"></asp:TextBox>
  63. <br />
  64. <asp:UpdatePanel ID="UpdatePanel2" runat="server">
  65. <ContentTemplate>
  66. <asp:CustomValidator ID="CustomValidator2" runat="server"
  67. ControlToValidate="rPsdText" ErrorMessage="*"
  68. onservervalidate="CustomValidator2_ServerValidate">
  69. </asp:CustomValidator>
  70. </ContentTemplate>
  71. </asp:UpdatePanel>
  72. <br />
  73. <asp:TextBox runat="server" ID="rrPsdText" TextMode="Password" Height="40px" Width="490px" CssClass="Tb" ></asp:TextBox>
  74. <br />
  75. <asp:UpdatePanel ID="UpdatePanel3" runat="server">
  76. <ContentTemplate>
  77. <asp:CustomValidator ID="CustomValidator3" runat="server"
  78. ControlToValidate="rrPsdText" ErrorMessage="*"
  79. onservervalidate="CustomValidator3_ServerValidate">
  80. </asp:CustomValidator>
  81. </ContentTemplate>
  82. </asp:UpdatePanel>
  83. <br />
  84. <table>
  85. <tr>
  86. <td>
  87. <asp:CheckBox ID="CheckBox1" runat="server" Checked="true" />
  88. </td>
  89. <td>
  90. <span>同意</span> <asp:LinkButton runat="server" Text="服务条款" ID="ckItem"></asp:LinkButton>
  91. </td>
  92. <td>
  93.                       
  94.                       
  95.       
  96. </td>
  97. <td>
  98. <asp:LinkButton ID="linkToLogin" runat="server" Text="已有账号?登录" OnClick="linkToLogin_Click"></asp:LinkButton>
  99. </td>
  100. </tr>
  101. </table>
  102. <asp:Button ID="btnRegister" runat="server" CssClass="transButton" Height="49px" Text="注 册" Width="500px" OnClick="btnRegister_Click" />
  103. </form>
  104. </body>
  105. <script type="text/javascript">
  106. function watermark(id, value) {
  107. var obj = document.getElementById(id);
  108. var isPsdMode = false;
  109. if (obj.type == "password")
  110. {
  111. obj.type = "text";
  112. isPsdMode = true;
  113. }
  114. obj.value = value;
  115. obj.style.color = "Gray";
  116. //获取焦点事件
  117. obj.onfocus = function () {
  118. obj.style.color = "Black";
  119. if (isPsdMode)
  120. {
  121. obj.type = "password";
  122. }
  123. if (this.value == value) {
  124. this.value = '';
  125. }
  126. };
  127. //失去焦点事件
  128. obj.onblur = function () {
  129. if (this.value == "") {
  130. if (isPsdMode) {
  131. obj.type = "text";
  132. }
  133. this.value = value;
  134. obj.style.color = "Gray";
  135. }
  136. else {
  137. obj.style.color = "Black";
  138. }
  139. };
  140. }
  141. window.onload = function () {
  142. var arr = [{ 'id': 'rUserNameText', 'desc': '用户名' }, { 'id': 'rPsdText', 'desc': '密码' },{ 'id': 'rrPsdText', 'desc': '确认密码' }];
  143. for (var i = 0; i < arr.length; i++) {
  144. watermark(arr[i].id, arr[i].desc);
  145. }
  146. };
  147. </script>
  148. </html>
复制代码

 

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

 

  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Drawing;
  5. namespace Album.OnlineAlbum
  6. {
  7. public partial class Register : System.Web.UI.Page
  8. {
  9. private bool UserNameIselgal = false;
  10. private bool PsdIselgal = false;
  11. private bool CanRegister = false;
  12. protected void Page_Load(object sender, EventArgs e)
  13. {
  14. }
  15. protected void linkToLogin_Click(object sender, EventArgs e)
  16. {
  17. Response.Redirect("Login.aspx");
  18. }
  19. protected void btnRegister_Click(object sender, EventArgs e)
  20. {
  21. Session["User"] = rUserNameText.Text;
  22. Session["Psd"] = rPsdText.Text;
  23. string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
  24. SqlConnection conn = new SqlConnection(connStr);
  25. try
  26. {
  27. conn.Open();
  28. SqlCommand cmd = new SqlCommand("select count(*) from UserTable where UId=@UId", conn);
  29. cmd.Parameters.Add("@UId", SqlDbType.Char);
  30. cmd.Parameters[0].Value = Session["User"];
  31. int count = (int)cmd.ExecuteScalar();
  32. if (count > 0)
  33. {
  34. Response.Write("<script>alert('用户名已存在!')</script>");
  35. }
  36. else
  37. {
  38. CanRegister = true;
  39. }
  40. }
  41. catch
  42. {
  43. Response.Write("检测重名异常");
  44. }
  45. finally
  46. {
  47. conn.Close();
  48. }
  49. if (CanRegister)
  50. {
  51. try
  52. {
  53. conn.Open();
  54. string strIns = "insert into UserTable(UId, Psd) values(@UId, @Psd)";
  55. SqlCommand cmd = new SqlCommand(strIns, conn);
  56. cmd.Parameters.Add("@UId", SqlDbType.NChar);
  57. cmd.Parameters.Add("@Psd", SqlDbType.NChar);
  58. cmd.Parameters["@UId"].Value = Session["User"];
  59. cmd.Parameters["@Psd"].Value = Session["Psd"];
  60. cmd.ExecuteNonQuery();
  61. }
  62. catch
  63. {
  64. Response.Write("注册异常");
  65. }
  66. finally
  67. {
  68. conn.Close();
  69. }
  70. }
  71. CanRegister = CanRegister && UserNameIselgal && PsdIselgal;
  72. if (CanRegister)
  73. {
  74. Session["CurrentUser"] = rUserNameText.Text;
  75. Response.Redirect("Home.aspx");
  76. }
  77. }
  78. protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
  79. {
  80. if (rUserNameText.Text.Equals("用户名"))
  81. {
  82. CustomValidator1.ErrorMessage = "*用户名为空";
  83. args.IsValid = false;
  84. } else if (System.Text.RegularExpressions.Regex.IsMatch(rUserNameText.Text, "^[0-9a-zA-Z]+$") &&
  85. rUserNameText.Text.Length > 5 && rUserNameText.Text.Length < 11)
  86. {
  87. args.IsValid = true;
  88. UserNameIselgal = true;
  89. }
  90. else
  91. {
  92. CustomValidator1.ErrorMessage = "*用户名由6~10位数字和字母构成";
  93. args.IsValid = false;
  94. }
  95. }
  96. protected void CustomValidator2_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
  97. {
  98. if (rPsdText.Text.Equals("密码"))
  99. {
  100. CustomValidator2.ErrorMessage = "*密码为空";
  101. args.IsValid = false;
  102. }
  103. else if (System.Text.RegularExpressions.Regex.IsMatch(rPsdText.Text, "^[0-9a-zA-Z]+$") &&
  104. rPsdText.Text.Length > 4)
  105. {
  106. args.IsValid = true;
  107. }
  108. else
  109. {
  110. CustomValidator2.ErrorMessage = "*密码由全数字和字母构成且不少于5位";
  111. args.IsValid = false;
  112. }
  113. }
  114. protected void CustomValidator3_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
  115. {
  116. if (rrPsdText.Text.Equals("") ||rrPsdText.Text.Equals("确认密码"))
  117. {
  118. args.IsValid = false;
  119. CustomValidator3.ErrorMessage = "*确认密码为空";
  120. }
  121. else if (!rrPsdText.Text.Equals(rPsdText.Text))
  122. {
  123. args.IsValid = false;
  124. CustomValidator3.ErrorMessage = "*两次密码不一致";
  125. }
  126. else
  127. {
  128. PsdIselgal = true;
  129. args.IsValid = true;
  130. }
  131. }
  132. }
  133. }
复制代码

    ②登录前台页面Login.aspx:

    

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Album.OnlineAlbum.Login" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  6. <title>登陆</title>
  7. <style>
  8. form{
  9. color:#575454;
  10. width:500px;
  11. margin: auto;
  12. font-size:15px;
  13. margin-top:260px;
  14. }
  15. #spanpsd{
  16. margin-left:125px;
  17. }
  18. #spanuser{
  19. margin-left:110px;
  20. }
  21. div{
  22. margin:30px auto;
  23. align-content:center;
  24. }
  25. .textbox{
  26. border:solid 1px;
  27. background:rgba(0, 0, 0, 0);
  28. }
  29. #LinkButton1{
  30. text-decoration:none;
  31. color:lightblue;
  32. margin-left:230px;
  33. }
  34. #Button1{
  35. border-radius:2px;
  36. border:solid 1px;
  37. background-color:transparent;
  38. margin-left:150px;
  39. margin-top:10px;
  40. }
  41. body{
  42. background-image: url("lbg.jpg");
  43. }
  44. </style>
  45. </head>
  46. <body>
  47. <form id="form1" runat="server">
  48. <div>
  49. <div>
  50. <span id="spanuser">用户名:</span>
  51. <asp:TextBox ID="TextBox1" runat="server" CssClass="textbox" Height="30px" Width="240px"></asp:TextBox>
  52. </div>
  53. <div>
  54. <span id="spanpsd">密码:</span>
  55. <asp:TextBox ID="TextBox2" runat="server" CssClass="textbox" Height="30px" Width="240px" TextMode="Password"></asp:TextBox>
  56. </div>
  57. <div>
  58. <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">没有账号?注册</asp:LinkButton>
  59. <br />
  60. <asp:Button ID="Button1" runat="server" Text="登 录" Width="270px" Height="40px" OnClick="Button1_Click" />
  61. </div>
  62. </div>
  63. </form>
  64. </body>
  65. </html>
复制代码

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

    

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.SqlClient;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. namespace Album.OnlineAlbum
  10. {
  11. public partial class Login : System.Web.UI.Page
  12. {
  13. protected void Page_Load(object sender, EventArgs e)
  14. {
  15. }
  16. protected void LinkButton1_Click(object sender, EventArgs e)
  17. {
  18. Response.Redirect("Register.aspx");
  19. }
  20. protected void Button1_Click(object sender, EventArgs e)
  21. {
  22. string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
  23. SqlConnection conn = new SqlConnection(connStr);
  24. try
  25. {
  26. conn.Open();
  27. SqlCommand cmd = new SqlCommand("select count(*) from UserTable where UId=@UId and Psd=@Psd", conn);
  28. cmd.Parameters.Add("@UId", SqlDbType.Char);
  29. cmd.Parameters.Add("@Psd", SqlDbType.Char);
  30. cmd.Parameters[0].Value = TextBox1.Text;
  31. cmd.Parameters[1].Value = TextBox2.Text;
  32. int count = (int)cmd.ExecuteScalar();
  33. if (count == 1)
  34. {
  35. Session["CurrentUser"] = TextBox1.Text;
  36. Response.Redirect("./Home.aspx");
  37. }
  38. else
  39. {
  40. Response.Write("<script>alert('用户名或密码错误')</script>");
  41. }
  42. }
  43. catch
  44. {
  45. Response.Write("<script>alert('登录异常')</script>");
  46. }
  47. finally
  48. {
  49. conn.Close();
  50. }
  51. }
  52. }
  53. }
复制代码

    ③Home.aspx:

    

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="Album.OnlineAlbum.Home" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  6. <title>Online Ablum</title>
  7. <style>
  8. #page_header{
  9. height:20px;
  10. margin-left:10px;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <form runat="server">
  16. <asp:LinkButton runat="server" OnClick="Unnamed2_Click" ID="btnToReg">注册</asp:LinkButton>
  17.  <asp:LinkButton runat="server" OnClick="Unnamed1_Click" ID="btnToLog">登录</asp:LinkButton>
  18. </form>
  19. </body>
  20. </html>
复制代码

    home.aspx.cs:

    

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. namespace Album.OnlineAlbum
  8. {
  9. public partial class Home : System.Web.UI.Page
  10. {
  11. protected void Page_Load(object sender, EventArgs e)
  12. {
  13. if (Session["CurrentUser"] != null)
  14. btnToReg.Text = Session["CurrentUser"].ToString();
  15. }
  16. protected void Unnamed1_Click(object sender, EventArgs e)
  17. {
  18. Response.Redirect("Login.aspx");
  19. }
  20. protected void Unnamed2_Click(object sender, EventArgs e)
  21. {
  22. Response.Redirect("Register.aspx");
  23. }
  24. }
  25. }    
复制代码

   Web.config:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!--
  3. 有关如何配置 ASP.NET 应用程序的详细信息,请访问
  4. http://go.microsoft.com/fwlink/?LinkId=169433
  5. -->
  6. <configuration>
  7. <connectionStrings>
  8. <add name="ConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
  9. providerName="System.Data.SqlClient" />
  10. </connectionStrings>
  11. <appSettings>
  12. <add key="ValidationSettings:UnobtrusiveValidationMode" value="none"/>
  13. </appSettings>
  14. <system.web>
  15. <compilation debug="true" targetFramework="4.5.2"/>
  16. <httpRuntime targetFramework="4.5.2"/>
  17. <httpModules>
  18. <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
  19. </httpModules>
  20. </system.web>
  21. <system.codedom>
  22. <compilers>
  23. <compiler language="c#;cs;csharp" extension=".cs"
  24. type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  25. warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
  26. <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
  27. type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  28. warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE="Web" /optionInfer+"/>
  29. </compilers>
  30. </system.codedom>
  31. <system.webServer>
  32. <validation validateIntegratedModeConfiguration="false"/>
  33. <modules>
  34. <remove name="ApplicationInsightsWebTracking"/>
  35. <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
  36. preCondition="managedHandler"/>
  37. </modules>
  38. </system.webServer>
  39. </configuration>
复制代码

 

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

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


来源:https://blog.csdn.net/Richard1997/article/details/79354090
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?会员注册

×
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 12:35 , Processed in 1.032225 second(s), 27 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表