mvc5生成图片验证码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;

namespace FinallyMvc.Handler
{
///
/// Handler1 的摘要说明
///
public class Handler1 : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.Clear();

        //定义一个字符串
        string strCode = "0123456789QWERTYUIOPLKJHGFDSAMNBVCXZqwertyuioplkjhgfdsazxcvbnm";

        string code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++)
        {
            code += strCode.Substring(random.Next(0, 62), 1);
        }

        //使用cookie保存验证码,cookie存在客户端
        context.Response.Cookies.Add(new HttpCookie("code", code));


        //生成图片
        using (Bitmap bitmap = new Bitmap(110, 40))
        {
            //画布
            Graphics graphics = Graphics.FromImage(bitmap);
            //设置背景
            graphics.FillRectangle(new SolidBrush(Color.Gray), 0, 0, 110, 40);

            //定义字体
            Font font = new Font("微软雅黑", 18.0f);
            //画图
            graphics.DrawString(code, font, new SolidBrush(Color.White), 5, 5);
            //向浏览器输出图片流
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            context.Response.ContentType = "image/jpeg";
        }

        context.Response.End();
    }

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

}

你可能感兴趣的:(mvc5生成图片验证码)