Captcha

<< Click to Display Table of Contents >>

Navigation:  ASP.NET > Dicas avançadas >

Captcha

Previous pageReturn to chapter overviewNext page

Tela

 

captcha

 

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></title>

</head>

<body>

  <form id="form1" runat="server">

  <div>

      <asp:Image ID="Image1" runat="server" ImageUrl="~/GerarCaptcha.aspx" Height="50px" Width="150px" />

      <br />

      <br />

      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

      &nbsp;<asp:Button ID="btnTestar" runat="server" OnClick="btnTestar_Click" Text="Testar" />

      <br />

  </div>

  <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

  </form>

</body>

</html>

 

Default.aspx.cs

 

using System;

using System.Web.UI;

 

public partial class _Default : System.Web.UI.Page

{

  protected void Page_Load(object sender, EventArgs e)

   {

   }

 

  protected void btnTestar_Click(object sender, EventArgs e)

   {

      if (Page.IsValid && (TextBox1.Text == Session["captcha"].ToString()))

       {

           Label1.Text = "Imagem validada com sucesso!";

       }

      else

       {

           Label1.Text = "Imagem incorreta!";

       }

   }

}

 

GerarCaptcha.aspx

 

(nada)

 

GerarCaptcha.aspx.cs

 

using System;

using System.Drawing;

using System.Drawing.Imaging;

using System.Drawing.Text;

 

public partial class GerarCaptcha : System.Web.UI.Page

{

  protected void Page_Load(object sender, EventArgs e)

   {

      // prepara os componentes de saída para desenho

      Bitmap bmp = new Bitmap(100, 20);

      Graphics grap = Graphics.FromImage(bmp);

 

      // limpa com cores loca

       grap.Clear(Color.BurlyWood);

       grap.TextRenderingHint = TextRenderingHint.SystemDefault;

 

      // gera randomicamente letras e números

      string senhaCaptcha = "";

      Random rand = new Random();

      for (int x = 0; x < 6; x++)

       {

           senhaCaptcha += (char)rand.Next(48, 122); // 48 = zero...  122 = z

       }

 

      // grava na variável de sessão

       Session.Add("captcha", senhaCaptcha);

 

      // desenha na tela

      Font fonte = new Font("Calibri", 14, FontStyle.Italic);

       grap.DrawString(senhaCaptcha, fonte, Brushes.OliveDrab, 1, 1);

 

      // manda pro response

       Response.ContentType = "image/gif";

       bmp.Save(Response.OutputStream, ImageFormat.Gif);

 

      // free willy

       grap.Dispose();

       fonte.Dispose();

       bmp.Dispose();

   }

}