当前位置:网站首页>ASP. Net authentication code login
ASP. Net authentication code login
2022-06-30 18:07:00 【Bailu-】
One . explain
This article is Xiaobai learning Morni Chang Teacher's video teaching <<Asp.Net WEB Server programming technology >> Study notes made in , Some knowledge points follow the tutorial , You can also go to the teacher's homepage to learn , Thank you. .
Two . Generate captcha image (CodeHandler.ashx)
Previous section , We use checkcode.aspx.cs To process the generated verification code image , Today we are Handler Folder to create a general handler CodeHandler.ashx, Instead of . The code is as follows :
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.SessionState;
namespace MyMusci.Handler
{
/// <summary>
/// CodeHandler Summary description of
/// </summary>
public class CodeHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string chkCode = string.Empty;
int ix, iy;
ix = 140;
iy = 40;
// Color list , Used for verification code 、 Noise line 、 noise
Color[] color = {
Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
// Font list , Used for verification code
string[] font = {
"Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "MingLiU", "Arial" };
// The character set of the captcha , Removed some confusing characters
char[] character = {
'2', '3', '4', '5', '6', '8', '9', '0', '1', ' Small ', ' white ' };
Random rnd = new Random();
// Generate captcha string
for (int i = 0; i < 4; i++)
{
chkCode += character[rnd.Next(character.Length)];
}
Bitmap bmp = new Bitmap(ix, iy);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
// Draw a noise line
for (int i = 0; i < 10; i++)
{
int x1 = rnd.Next(ix);
int y1 = rnd.Next(iy);
int x2 = rnd.Next(ix);
int y2 = rnd.Next(iy);
Color clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
// Draw the verification code string
for (int i = 0; i < chkCode.Length; i++)
{
string fnt = font[rnd.Next(font.Length)];
Font ft = new Font(fnt, iy/2, FontStyle.Bold);
Color clr = color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 30 + 2, (float)2);
}
// Painting noise
for (int i = 0; i < 50; i++)
{
int x = rnd.Next(bmp.Width);
int y = rnd.Next(bmp.Height);
Color clr = color[rnd.Next(color.Length)];
bmp.SetPixel(x, y, clr);
}
// Write the verification code to SESSION, Why can't the second page get the value ???
// General handler adds interface file ;
HttpContext.Current.Session["Code"] = chkCode.ToUpper();
// Clear the page output cache , Set this page to have no cache
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
context.Response.Expires = 0;
context.Response.CacheControl = "no-cache";
context.Response.AppendHeader("Pragma", "No-Cache");
// Write the verification code image to the memory stream , And put it in "image/Png" Format output
// My page returns pictures ;
MemoryStream ms = new MemoryStream();
try
{
bmp.Save(ms, ImageFormat.Png);
context.Response.ClearContent();
context.Response.ContentType = "image/Png";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
// Explicitly release resources
bmp.Dispose();
g.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
3、 ... and . Add verification code to the login page (login_new.aspx)
Because we changed the verification code generator , Therefore, you should also change the corresponding code in the login interface :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login_new.aspx.cs" Inherits="MyMusci.login_new" %>
<!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>
<link href="bootstrap-5.1.3-dist/css/bootstrap.css" rel="stylesheet" />
<script src="bootstrap-5.1.3-dist/js/bootstrap.bundle.js"></script>
<script src="js/jquery.js"></script>
<style> /* Log in the entire div Vertical center */ .all {
width: 700px; height: 260px; background-color: rgba(205,197,191,0.8); position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; padding:0; } body {
background-image: url("img/dm.jpg"); /* The whole picture as the background , Not enough auto stretch */ background-size: cover; } </style>
</head>
<body>
<form id="form1" runat="server">
<div class="container mt-3">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table class="table all">
<tr>
<td class="table-primary display-3 text-center text-primary" colspan="3"> Login screen </td>
</tr>
<tr>
<td> Account </td>
<td>
<asp:TextBox ID="userName" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="rfv_useName" runat="server" ControlToValidate="userName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ForeColor="Red"> Account cannot be empty </asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev_userName" runat="server" ControlToValidate="userName" Display="Dynamic" ErrorMessage="RegularExpressionValidator" ForeColor="Red" ValidationExpression="\w{5,13}"> The account you entered is abnormal (5-12 position )</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="auto-style2"> password </td>
<td class="auto-style2">
<asp:TextBox ID="userPwd" runat="server"></asp:TextBox>
</td>
<td class="auto-style2">
<asp:RequiredFieldValidator ID="rfv_userPwd" runat="server" ControlToValidate="userPwd" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ForeColor="Red"> The password cannot be empty </asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="rev_userPwd" runat="server" ControlToValidate="userPwd" Display="Dynamic" ErrorMessage="RegularExpressionValidator" ForeColor="Red" ValidationExpression="\w{8,13}"> The password you entered is abnormal (8 position )</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
Verification Code </td>
<td>
<asp:TextBox ID="code" runat="server"></asp:TextBox>
</td>
<td><img id="imgcode" src="Handler/CodeHandler.ashx" />
<asp:Label ID="codeText" runat="server" Text=""></asp:Label></td>
</tr>
<tr>
<td>
<asp:Button ID="btn_sub" runat="server" class="btn btn-primary" OnClick="btn_sub_Click" Text=" Sign in " />
</td>
<td>
<asp:LinkButton ID="LinkButton1" runat="server" class="btn btn-secondary" PostBackUrl="~/RegUser.aspx" CausesValidation="False"> register </asp:LinkButton>
</td>
<td> </td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
<script> // Picture click event $("#imgcode").click(function () {
$("#imgcode").attr("src", "Handler/CodeHandler.ashx?t=" + Math.random()); }) </script>
</body>
</html>
The background code is also added as the corresponding code (login_new.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.Data;
using System.Collections;
namespace MyMusci
{
public partial class login_new : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// Reset button click event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btn_reset_Click(object sender, EventArgs e)
{
userName.Text = "";
userPwd.Text = "";
}
/// <summary>
/// Login button click event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btn_sub_Click(object sender, EventArgs e)
{
// test
//if ("administrator".Equals(userName.Text) && "12345678".Equals(userPwd.Text)) {
// Response.Redirect("index.aspx");
//}
// Here, it is determined whether the validation control passes , If not , Then return to
if (!rev_userName.IsValid || !rev_userPwd.IsValid) {
return;
}
// Here, it is judged whether the user has entered the value of the input box of the verification code , If there is no input , Prompt the user , And back to
if (code.Text != Session["Code"].ToString())
{
codeText.Text = " The verification code is incorrect , Please re-enter ";
return;
}
// Otherwise, clear the prompt value , And let the code run normally
else {
codeText.Text = "";
}
string sql = "SELECT COUNT(*) FROM user_all WHERE user_name=?name AND user_pwd=?pwd";
Hashtable ht = new Hashtable();
ht.Add("name", userName.Text.ToString());
ht.Add("pwd", ChangPwd.UserMd5(userPwd.Text.ToString()));
int resilc = ToolMysqlDate.excutScal(sql, ht);
if (resilc > 0)
{
// Bind the user name to Session
Session["userName"] = userName.Text.ToString();
//Response Is the response from the server , Consume resources , Server memory and network bandwidth
//Response.Redirect("index.aspx");
ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "ok_login", "alert(' You have successfully signed in !');location.href='index.aspx'", true);
}
else
{
//Response.Write("<script>alert(' The account or password you entered is incorrect , Please check and enter !!!')</script>");
ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "error_login", "alert(' The account or password you entered is incorrect , Please check and enter !!!')", true);
}
}
}
}
Four . effect

When the verification passes , And the verification code is correct :
When the verification code is incorrect :
边栏推荐
- The gates of Europe
- Add code block in word (Reprint)
- Conception d'un centre commercial en ligne basé sur SSH
- Key to understanding the trend of spot Silver
- Thinking on large file processing (upload, download)
- Redis (VIII) - enterprise level solution (I)
- 自旋锁探秘
- 基于eNSP的校园网设计的仿真模拟
- TFTP下载kernel,nfs挂载文件系统
- 巴比特 | 元宇宙每日必读:未成年人打赏后要求退款,虚拟主播称自己是大冤种,怎么看待这个监管漏洞?...
猜你喜欢

Canvas mouse control gravity JS effect

Redis (IX) - enterprise level solution (II)

2022上半年盘点:20+主流数据库重大更新及技术要点汇总

Hyper-V: enable SR-IOV in virtual network

IEEE TBD SCI impact factor increased to 4.271, ranking Q1!

A tough battle for Tencent cloud

Redis (I) - data type

5g has been in business for three years. Where will innovation go in the future?

Development: how to install offline MySQL in Linux system?

News management system based on SSM
随机推荐
Six pictures show you why TCP has three handshakes?
ABAP publish restful service
Combination of applet container and Internet of things
Lenovo's "dual platform" operation and maintenance solution helps to comprehensively improve the intelligent management ability of the intelligent medical industry
K-line diagram interpretation and practical application skills (see position entry)
Inventory in the first half of 2022: summary of major updates and technical points of 20+ mainstream databases
零基础也能做Apple大片!这款免费工具帮你渲染、做特效、丝滑展示
Canvas cloud shape animation
Nielseniq welcomes dawn E. Norvell, head of retail lab, to accelerate the expansion of global retail strategy
6 张图带你搞懂 TCP 为什么是三次握手?
[sword finger offer] sword finger offer 53 - ii Missing numbers from 0 to n-1
Development details of NFT casting trading platform
5g has been in business for three years. Where will innovation go in the future?
Deep understanding of JVM (V) - garbage collection (II)
Deep understanding of JVM (IV) - garbage collection (I)
现在玩期货需要注意什么,在哪里开户比较安全,我第一次接触
基於SSH的網上商城設計
Grep output with multiple colors- Grep output with multiple Colors?
Share 5 commonly used feature selection methods, and you must see them when you get started with machine learning!!!
MIT science and Technology Review released the list of innovators under the age of 35 in 2022, including alphafold authors, etc