MVC生成验证码

请看大屏幕

@using System.Drawing
@using System.Drawing.Imaging
@using System.Drawing.Drawing2D
@using System.IO
@{ 
    Layout = null;
    /*
     * 输入参数:ViewBag.ValidateCode 验证码
     * 输出:流输出图片
     */
    string code = ViewBag.ValidateCode;
    Bitmap image = new Bitmap((int)Math.Ceiling(code.Length * 16.5), 30);
    Graphics g = Graphics.FromImage(image);
    try
    {
        //生成随机生成器        
        Random random = new Random();
        //清空图片背景色
        g.Clear(Color.White);
        //画图片的干扰线
        for (int i = 0; i < 30; 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 Font("Arial", 16, (FontStyle.Bold | FontStyle.Italic));
        LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
            Color.Blue, Color.DarkRed, 1.2f, true);
        //绘制验证码
        g.DrawString(code, font, brush, 3, 2);
        //画图片的前景干扰点
        for (int i = 0; i < 200; i++)
        {
            int x = random.Next(image.Width);
            int y = random.Next(image.Height);
            image.SetPixel(x, y, Color.FromArgb(random.Next()));
        }
        //画图片的边框线
        g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
        //保存图片数据
        MemoryStream stream = new MemoryStream();
        image.Save(stream, ImageFormat.Jpeg);
        //输出图片
        Response.Clear();
        Response.ContentType = "image/jpeg";
        Response.BinaryWrite(stream.ToArray());

    }
    finally
    {
        g.Dispose();
        image.Dispose();
    }
}

 分布视图代码

@*
    ==========================================
    验证码部件
    ==========================================
     1、验证码输入框(input)
     2、验证码显示(img)class="border_no code"
     3、验证码id隐藏域(hidden)
*@
@{ 
    @Html.Raw("<span class='code' style='padding:20px 2px 0px 20px;'></span><input  id='checkcode' name='checkcode' type='text' style='width:120px; ' placeholder='验证码' ValidateType='Customer' TipID='ValidateCode_PasswordTip'  NotEmpty='true' MinLength='1'  class='border_no' OnFocusTip='验证码必填' OnErrorTip='格式错误' />");
    @Html.Raw("<img id='ValidateCode' title='换一张' onclick='GetNewValidateCode()'  src='/ValidateCodeImage/ShowCode?id=" + entity.ID + "' align='absmiddle'/>");
    @Html.Raw("<input id='ValidateCode_ID' name='ValidateCode_ID' type='hidden' value='" + entity.ID + "'/>");
    @Html.Raw("<span id='ValidateCode_PasswordTip'></span>");
                                                            
}
@*<script type="text/javascript" language="javascript" src='"jquery-1.6.min.js")'></script>*@
<script>
    function GetNewValidateCode() {
        $.ajax({
            type: "POST",
            url: '@Html.ActionHref("GetNewValidateCode", "ValidateCodeImage",new {area=""})',
            async: false,
            success: function (ret) {
                var id = ret.id;
                $("#ValidateCode").attr("src", "/ValidateCodeImage/ShowCode?id=" + id);
                $("#ValidateCode_ID").val(id);
            }
        });
    }
</script>

后台代码

    public class ValidateCodeImageController : Controller
    {
        /// <summary>
        /// 展示验证码
        /// </summary>
        /// <param name="id">令牌</param>
        /// <returns>验证码图片</returns>
        [HttpGet]
        public ActionResult ShowCode(string id)
        {
            //调用验证码服务获取验证码
            PasswordCard entity = XXXGet(id);
            if (entity == null)
            {
                throw new Exception("对不起,没有获取到验证码!");
            }
            //视图调用:入口参数
            ViewBag.ValidateCode = entity.PassWord;
            return View("~/Views/Shared/WebParts/ValidateCodeImage.cshtml");
        }

        public JsonResult GetNewValidateCode()
        {
            PasswordCard entity = ValidateCodeService.Apply();
            ViewBag.ValidateCode = entity.PassWord;
            return Json(new { id = entity.ID });
        }

    }

调用方式

  @RenderPage("~/Views/Shared/XXX/分部视图")

posted @ 2015-10-29 15:50  若云  阅读(316)  评论(1编辑  收藏  举报