asp.Net学習ノート・単純検証コードの実現

2809 ワード

Sessionで判断する
 
一般的なプロセッサで検証コードを生成し、Imageコントロールに設定してユーザーが入力した数字と比較し、正しくなければ生成検証コードを再呼び出し、暴利な検証コードの解読を防ぐ
このプログラムは個人がSessionを学ぶためにテストするだけで、専門の検証コードプログラムではありません
一般的なハンドラのコードは以下の通りです.
<%@ WebHandler Language="C#" Class="IdentifyingCode" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
public class IdentifyingCode : IHttpHandler,System.Web.SessionState.IRequiresSessionState
//             Session,    System.Web.SessionState.IRequiresSessionState  ,           
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        
        //Bitmap bitmap = new Bitmap(300, 100);
        Bitmap bitmap = GetImg();
        bitmap.Save(context.Response.OutputStream, ImageFormat.Jpeg);

    }

    /// <summary>
    ///        
    /// </summary>
    /// <returns>     </returns>
    public Bitmap GetImg()
    {
        //     
        Random random  = new Random(System.DateTime.Now.Second);//      
        int num = random.Next(1000, 9999);
        HttpContext.Current.Session["idenfyCode"] = num;//         session 
        Bitmap bitMap = new Bitmap(300, 100);//    

        Graphics graphics = Graphics.FromImage(bitMap);//  

        graphics.DrawString(num.ToString(), new Font("  ", 20), new SolidBrush(Color.Blue), new PointF(0, 0));
        return bitMap;


    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

そして、WebフォームのバックグラウンドC#コードは以下の通りです.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class IdentifyingCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Image1.ImageUrl = "IdentifyingCode.ashx";
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        // session                  
        if (Session["idenfyCode"].ToString() == TextBox1.Text)
        {
            Response.Write("    ");
        }
        else
        {
            //                   ,      
            this.Image1.ImageUrl = "IdentifyingCode.ashx";
        }
    }
}