>  기사  >  백엔드 개발  >  확인 코드 기능을 구현하기 위해 ashx를 사용하는 asp.net에 대한 자세한 설명

확인 코드 기능을 구현하기 위해 ashx를 사용하는 asp.net에 대한 자세한 설명

巴扎黑
巴扎黑원래의
2017-08-15 13:54:362268검색

이 글에서는 asp.net에서 ashx를 사용하여 그래픽 인증 코드를 생성하는 방법을 주로 소개하며, 필요한 친구들이 참고할 수 있는 그래픽 인증 코드를 생성하기 위한 asp.net의 단계, 구현 방법 및 관련 주의 사항을 분석합니다. 이 기사

이 예에서는 asp.net이 ashx를 사용하여 그래픽 확인 코드를 생성하는 방법을 설명합니다. 참고하실 수 있도록 공유해 드리며, 자세한 내용은 다음과 같습니다.

인증코드의 장점은 굳이 설명하지 않아도 다들 아실 텐데요. 인터넷에서 누군가가 aspx 페이지에 직접 인증 코드를 작성한 것을 보았는데, 이는 이러한 방식으로 인증 코드를 요청하는 것이 페이지를 요청하는 것과 동일하다는 것을 의미합니다. 아래와 같이


<form id="form1" runat="server">
  <p>
    <asp:Image ID="Image1" runat="server" ImageUrl="Default.aspx" />
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
  </p>
</form>

이 코드를 보면 코드를 작성한 사람이 벌을 받아야 한다는 느낌이 듭니다. 확인을 위해 일부 스크립트를 작성하지 마십시오.

이제 그러한 기능을 구현하는 방법을 소개하겠습니다

1. ashx를 작성하여 그래픽 인증 코드를 생성합니다


using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.SessionState;
using System.Drawing;
namespace usechecknum.ashx
{
  /// <summary>
  /// $codebehindclassname$ 的摘要说明
  /// </summary>
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class doCreateNum : IHttpHandler,IRequiresSessionState
  {
    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "text/html";
      string checkCode = GetValidation(5); // 产生5位随机验证码字符
      context.Session["Code"] = checkCode; //将字符串保存到Session中,以便需要时进行验证
      System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22);
      Graphics g = Graphics.FromImage(image);
      try
      {
        //生成随机生成器
        Random random = new Random();
        //清空图片背景色
        g.Clear(Color.White);
        // 画图片的背景噪音线
        int i;
        for (i = 0; i < 25; i++)
        {
          int x1 = random.Next(image.Width);
          int x2 = random.Next(image.Width);
          int y1 = random.Next(image.Height);
          int y2 = random.Next(image.Height);
          g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
        }
        Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);
        g.DrawString(checkCode, font, brush, 2, 2);
        //画图片的前景噪音点
        g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        context.Response.ClearContent();
        context.Response.ContentType = "image/Gif";
        context.Response.BinaryWrite(ms.ToArray());
      }
      finally
      {
        g.Dispose();
        image.Dispose();
      }
    }
    public string GetValidation(int num)
    {
      string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //"或者写汉字也行"
      string validatecode = "";
      Random rd = new Random();
      for (int i = 0; i < num; i++)
      {
        validatecode += str.Substring(rd.Next(0, str.Length), 1);
      }
      return validatecode;
    }
    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
}

2. 그래픽을 생성하므로 페이지에 인증 코드를 표시합니다. 79d7c95122630a3791db16c5259dc98d 태그에 간단한 스크립트만 작성하면 마우스 클릭만으로 인증코드가 전환됩니다


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="usechecknum._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>验证码的使用</title>
</head>
<script language="javascript" type="text/javascript">
  function changeCode() {
    var imgNode = document.getElementById("vimg");
    imgNode.src = "ashx/doCreateNum.ashx?t=" + (new Date()).valueOf(); // 这里加个时间的参数是为了防止浏览器缓存的问题
  }
  </script>
<body>
  <form id="form1" runat="server">
   请输入验证码:<input type="text" name="checknum"/><img src="ashx/doCreateNum.ashx" id="vimg" onclick="changeCode()" />
  </form>
</body>
</html>

오랜 시간 이야기를 나눈 후, 생성된 인증 코드는 다음과 같습니다

위 내용은 확인 코드 기능을 구현하기 위해 ashx를 사용하는 asp.net에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.