MVC4中的自定义Captcha图像刷新

时间:2014-01-06 07:47:17

标签: asp.net-mvc-4

控制器代码:

public class CaptchaImageResult : ActionResult
{
    public string GetCaptchaString(int length)
    {
        int intZero = '0';
        int intNine = '9';
        int intA = 'A';
        int intZ = 'Z';
        int intCount = 0;
        int intRandomNumber = 0;
        string strCaptchaString = "";
        Random random = new Random(System.DateTime.Now.Millisecond);
        while (intCount < length)
        {
            intRandomNumber = random.Next(intZero, intZ);
            if (((intRandomNumber >= intZero) && (intRandomNumber <= intNine) || (intRandomNumber >= intA) && (intRandomNumber <= intZ)))
            {
                strCaptchaString = strCaptchaString + (char)intRandomNumber;
                intCount = intCount + 1;
            }
        }
        return strCaptchaString;
    }
    public override void ExecuteResult(ControllerContext context)
    {
        Bitmap bmp = new Bitmap(100, 30);
        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.Navy);
        string randomString = GetCaptchaString(6);
        context.HttpContext.Session["captchastring"] = randomString;
        g.DrawString(randomString, new Font("Courier", 16), new SolidBrush(Color.WhiteSmoke), 2, 2);
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = "image/jpeg";
        bmp.Save(response.OutputStream, ImageFormat.Jpeg);
        bmp.Dispose();
    }
}
  [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
    public CaptchaImageResult ShowCaptchaImage(string random)
    {

        return new CaptchaImageResult();
    }

在视图中我的代码是:

  <img id="CaptchaImg" src="@Url.Action("ShowCaptchaImage", "Login", new { random = Guid.NewGuid().ToString() })" alt="" />
 <img src="~/Content/images/refresh-ico.ico" style="cursor: pointer;" id="refresh" height="30" width="30" alt="refresh" />

On Refresh Image单击以下执行的JQuery代码:

$("#refresh").click(function () {


    $.ajax({
        type: "GET",
        url: '@Url.Action("ShowCaptchaImage", "Login", new { random = Guid.NewGuid().ToString() })',
            contentType: "image/png",
            cache: false,
            success: function (data) {
                debugger;
                alert(data);

                var img = $('<img id="CaptchaImg" alt="" '); //Equivalent: $(document.createElement('img'))
                img.attr('src', '@Url.Action("ShowCaptchaImage", "Login", new { random = Guid.NewGuid().ToString() })');
            //$("#test").html('');
            img.appendTo('#test');
        }
        });
});

图像不令人耳目一新。请帮忙。 我使用OutputCache false并且每次都发送带有查询字符串的唯一URL。 但没有成功。

1 个答案:

答案 0 :(得分:0)

//Put This one Partial view
<img src="@Url.Action("GetCaptchaImage", "Vulpith_Public",new { dt=@DateTime.Now},Request.Url.Scheme)" />
<br /><input type="button" value="reload" onclick="Captcharefresh();" />



//And call ajax from this partial view as following
function Captcharefresh() {
    $.ajax({
                 url: "../Vulpith_Public/_GetCaptcha",
                 type: "post",
                 dataType: "html",
                 data: {},
    success: function (data) {
        $('#codeRefresh').html(data)
    },
    error: function (data) {
    }
});
}


//and create actions as following

public FileResult GetCaptchaImage(DateTime dt)
    {
        CaptchaRandomImage CI = new CaptchaRandomImage();
        this.Session["CaptchaImageText"] = CI.GetRandomString(5); // here 5 means I want to get 5 char long captcha
        //CI.GenerateImage(this.Session["CaptchaImageText"].ToString(), 300, 75);
        // Or We can use another one for get custom color Captcha Image 
        CI.GenerateImage(this.Session["CaptchaImageText"].ToString(), 300, 75, Color.DarkGray, Color.White);
        MemoryStream stream = new MemoryStream();
        CI.Image.Save(stream, ImageFormat.Png);
        stream.Seek(0, SeekOrigin.Begin);
        return new FileStreamResult(stream, "image/png");
    }

//One more action as
[HttpPost]
    public ActionResult _GetCaptcha()
    {
        return PartialView();
    }