Asp.net mvc 4 MVC4中的自定义验证码图像刷新

Asp.net mvc 4 MVC4中的自定义验证码图像刷新,asp.net-mvc-4,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 i

控制器代码:

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();
    }
公共类CaptchaImageResult:ActionResult
{
公共字符串GetCaptchaString(整数长度)
{
intZero='0';
intNine='9';
int intA='A';
intZ='Z';
int计数=0;
int intRandomNumber=0;
字符串strcaptchString=“”;
Random Random=新随机数(System.DateTime.Now.毫秒);
while(整数<长度)
{
intRandomNumber=random.Next(intZero,intZ);
如果((intrandomname>=intZero)&&&(intrandomname=intA)&&(intrandomname
//将这一部分视图

//并从这个局部视图调用ajax,如下所示 函数Captcharefresh(){ $.ajax({ url:“../Vulpith\u Public/\u GetCaptcha”, 类型:“post”, 数据类型:“html”, 数据:{}, 成功:功能(数据){ $('#codeRefresh').html(数据) }, 错误:函数(数据){ } }); } //并创建如下操作 公共文件结果GetCaptchaImage(日期时间dt) { CaptchaRandomImage CI=新的CaptchaRandomImage(); this.Session[“CaptchaImageText”]=CI.GetRandomString(5);//这里5表示我想获得5个字符长的验证码 //CI.GenerateImage(this.Session[“CaptchaImageText”].ToString(),300,75); //或者我们可以使用另一个来获取自定义颜色验证码图像 CI.GenerateImage(this.Session[“CaptchaImageText”].ToString(),300,75,Color.DarkGray,Color.White); MemoryStream stream=新的MemoryStream(); 保存(流,ImageFormat.Png); stream.Seek(0,SeekOrigin.Begin); 返回新文件streamresult(流,“image/png”); } //还有一个动作 [HttpPost] 公共行动结果_GetCaptcha() { 返回PartialView(); }
ShowCatpchaImage
的结果是
image/jpeg
内容类型。不是文本,您不能将
img
标记的
src
属性设置为二进制数据,它必须是图像的URL。我正在使用以下代码设置URL:img.attr('src','@URL.Action(“ShowCaptchaImage”,“Login”,new{random=Guid.NewGuid().ToString()}'));请建议怎么做。事实上,现在我看,
@Url.Action
毕竟返回了一个Url,或者应该返回。也许你的javascript没有被razor引擎解析,所以
@Url.Action
指令没有被解析。你在做任何调试吗?刷新点击处理程序正在执行吗?它是否发送请求?发送请求的地址是什么?您正在使用浏览器开发工具吗?(F12)嘿,谢谢你的回答。是的,我调试了我的ajax请求,它的刷新点击被触发了两次。我想这是因为我在ajax请求中提到的url,第二次由于@url.Action,它再次被触发。我正在发送唯一的guid和请求,因为我从internet上读到了关于这一点的信息,每次刷新验证码时都会生成唯一的url。但这适用于第一次刷新,请使用新GUID单击。但当我再次按刷新时(第二次、第三次等)GUID保持不变。我不知道为什么。GUID保持不变,因为您没有做任何更改。当第一次请求页面时,
@Url.Action
指令在服务器端呈现Url一次,但除非刷新整个页面,否则不会再次呈现Url。不过,为什么要依赖客户端发送随机字符串,为什么不直接使用服务器随机的?
  <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" />
$("#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');
        }
        });
});
//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();
    }