验证码实例

default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="UserName"></asp:Label>
    <asp:TextBox ID="tbUserName" runat="server" Height="22px" Width="128px"></asp:TextBox>
    <br />
    <asp:Label ID="Label2" runat="server" Text="PassPort"></asp:Label>
    <asp:TextBox ID="tbPassPort" runat="server" EnableTheming="True"
        TextMode="Password"></asp:TextBox>
    <br />
    ValidateCode<asp:TextBox ID="tbValidateCode" runat="server"
        EnableTheming="True"></asp:TextBox>
        <img width="100px" height="25px" src="ValidateImageHandler.ashx"/>
    <br />
    <asp:Button ID="btLogin" runat="server" οnclick="btLogin_Click" Text="Login" />
    <br />
    <asp:Label ID="lblResult" runat="server"></asp:Label>
    </form>
</body>
</html>

default.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
using System.Data.SqlClient;
using System.Data.Common;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection m_Sqlconn;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.tbUserName.Text = "";
            this.tbPassPort.Text = "";
        }
            DBConnect();
    }

    public static bool CheckCode(string text)
    {
        string txt = System.Web.HttpContext.Current.Session["strIdentify"] as string;
        return text == txt;
    }

    protected void btLogin_Click(object sender, EventArgs e)
    {
        string l_strUserName = this.tbUserName.Text.Trim();
        string l_strPassPort = this.tbPassPort.Text.Trim();
        string l_strValidateCode = this.tbValidateCode.Text.Trim();

        string l_sqlTemp = "select * from tbl_user where username = '" + l_strUserName + "' and [password] = '" + l_strPassPort + "'";

        SqlCommand comm = new SqlCommand(l_sqlTemp, m_Sqlconn);


        if (comm.ExecuteScalar() != null && CheckCode(l_strValidateCode))
        {

            this.lblResult.Text = "登陆成功";

        }

        else
        {
            //this.lblResult.Text = System.Web.HttpContext.Current.Session["strIdentify"] as string;

            this.lblResult.Text="用户登录信息错误,请重新输入";

        }
        m_Sqlconn.Close();
    }

    public void DBConnect()
    {
        string conn = System.Configuration.ConfigurationSettings.AppSettings["DBConnectString"];// "Server=127.0.0.1;user id=sa;password=sa;DataBase=test";

        m_Sqlconn = new SqlConnection(conn);

        try

        {
            m_Sqlconn.Open();
        }

        catch(Exception e)

        {
            this.lblResult.Text = e.ToString();
        }
    }
}

ValidateImageHandler.ashx

<%@ WebHandler Language="C#" Class="ValidateImageHandler" %>

 using System;
 using System.Web;
 using System.Web.SessionState;
 using System.Drawing;
 using System.Drawing.Imaging;
 using System.Text;
 
 /// <summary>
 /// ValidateImageHandler 生成网站验证码功能
 /// </summary>
 public class ValidateImageHandler : IHttpHandler, IRequiresSessionState
 {
     int intLength = 4;               //长度
     string strIdentify = "Identify"; //随机字串存储键值,以便存储到Session中
     public ValidateImageHandler()
     {       
     }
 
     /// <summary>
     ///  生成验证图片核心代码
     /// </summary>
     /// <param name="hc"></param>
     public void ProcessRequest(HttpContext hc)
     {
        //设置输出流图片格式
         hc.Response.ContentType = "image/gif";
        
         Bitmap b = new Bitmap(200, 60);
         Graphics g = Graphics.FromImage(b);
         g.FillRectangle(new SolidBrush(Color.YellowGreen), 0, 0, 200, 60);
         Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
         Random r = new Random();
 
         //合法随机显示字符列表
         string strLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
         StringBuilder s = new StringBuilder();
       
        //将随机生成的字符串绘制到图片上
         for (int i = 0; i < intLength; i++)
          {
             s.Append(strLetters.Substring(r.Next(0, strLetters.Length - 1), 1));
             g.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(0, 15));
         }
 
         //生成干扰线条
         Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
         for (int i = 0; i < 1; i++)
         {
             g.DrawLine(pen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
        }
         b.Save(hc.Response.OutputStream, ImageFormat.Gif);
         hc.Session["strIdentify"] = s.ToString(); //先保存在Session中,验证与用户输入是否一致
         hc.Response.End();
   
     }
    
     /// <summary>
     /// 表示此类实例是否可以被多个请求共用(重用可以提高性能)
     /// </summary>
     public bool IsReusable
     {
         get
         {
             return true;
         }
     }
 }

Web.config

  <appSettings>
    <add key="DBConnectString" value="Server=127.0.0.1;user id=sa;password=sa;DataBase=test"/>
  </appSettings>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 Android 短信验证码实例: 1. 在 AndroidManifest.xml 文件中添加短信权限: ```xml <uses-permission android:name="android.permission.RECEIVE_SMS" /> ``` 2. 创建一个广播接收器 SmsReceiver.java: ```java public class SmsReceiver extends BroadcastReceiver { private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; @Override public void onReceive(Context context, Intent intent) { if (SMS_RECEIVED_ACTION.equals(intent.getAction())) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); if (pdus != null && pdus.length > 0) { SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } String messageBody = messages[0].getMessageBody(); // 在这里处理收到的短信验证码 } } } } } ``` 3. 在你的 Activity 中注册 SmsReceiver: ```java public class MainActivity extends AppCompatActivity { private static final int SMS_REQUEST_CODE = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 请求短信权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_SMS}, SMS_REQUEST_CODE); } // 注册 SmsReceiver IntentFilter filter = new IntentFilter(SmsReceiver.SMS_RECEIVED_ACTION); filter.setPriority(1000); registerReceiver(new SmsReceiver(), filter); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == SMS_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 短信权限已经授权 } } } ``` 4. 在你的服务器端发送短信验证码并等待用户输入,然后在收到短信验证码后,将验证码发送给你的应用程序。当应用程序接收到短信验证码时,可以在 SmsReceiver 中处理该验证码。 以上是一个简单的 Android 短信验证码实例,希望对你有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值