当前位置:网站首页>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 :
边栏推荐
- [PROJECT] Xiaomao school (IX)
- Post penetration file system + uploading and downloading files
- Redis (VII) - sentry
- New skill: accelerate node through code cache JS startup
- Radio and television 5g officially set sail, attracting attention on how to apply the golden band
- Php8.0 environment detailed installation tutorial
- 元宇宙带来的游戏变革会是怎样的?
- Generate confrontation network, from dcgan to stylegan, pixel2pixel, face generation and image translation.
- Canvas cloud shape animation
- Conception d'un centre commercial en ligne basé sur SSH
猜你喜欢

Deep understanding of JVM (V) - garbage collection (II)

Add code block in word (Reprint)

TCP session hijacking based on hunt1.5

Redis (II) -- persistence
![Ten thousand volumes - list sorting [01]](/img/d4/124101b919a4d8163a32fc0f158efa.png)
Ten thousand volumes - list sorting [01]

Mo Tianlun salon | Tsinghua qiaojialin: Apache iotdb, originated from Tsinghua, is building an open source ecological road

Babbitt | yuanuniverse daily must read: minors ask for a refund after a reward. The virtual anchor says he is a big wrongdoer. How do you think of this regulatory loophole

Develop those things: how to add text watermarks to videos?

Vue3 reactive database

Solution: STM32 failed to parse data using cjson
随机推荐
ABAP-发布Restful服务
腾讯云安装mysql数据库
MySQL之零碎知识点
巴比特 | 元宇宙每日必读:未成年人打赏后要求退款,虚拟主播称自己是大冤种,怎么看待这个监管漏洞?...
Synchronized summary
TFTP download kernel, NFS mount file system
Daily interview 1 question - basic interview question of blue team - emergency response (1) basic idea process of emergency response +windows intrusion screening idea
Redis (VI) - master-slave replication
[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
Php8.0 environment detailed installation tutorial
Nft: unlimited possibilities to open the era of encryption Art
大文件处理(上传,下载)思考
Combination of applet container and Internet of things
Horizontal visual error effect JS special effect code
如何写一个技术方案
Rainbow Brackets 插件的快捷键
每日面试1题-如何防止CDN防护被绕过
Distributed machine learning: model average Ma and elastic average easgd (pyspark)
[bjdctf2020]the mystery of ip|[ciscn2019 southeast China division]web11|ssti injection
生成对抗网络,从DCGAN到StyleGAN、pixel2pixel,人脸生成和图像翻译。