0

我有图像验证码,并且在除 chrome 之外的所有浏览器中,验证码总是重新加载相同的图片。我该如何解决这个问题。Mb 我需要将我的图像转换为 base64string,我尝试将 nocache 属性设置为我的控制器/操作,但它不起作用.

public ActionResult CaptchaImageComm(string prefix, bool noisy = false)
    {
        var rand = new Random((int)DateTime.Now.Ticks);
        //generate new question
        int a = rand.Next(10, 99);
        int b = rand.Next(0, 9);
        var captcha = string.Format("{0} + {1} = ?", a, b);

        //store answer
        Session["Captcha5"] = a + b;

        //image stream
        FileContentResult img = null;
        string result = null;
        using (var mem = new MemoryStream())
        using (var bmp = new Bitmap(130, 30))
        using (var gfx = Graphics.FromImage((System.Drawing.Image)bmp))
        {
            gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
            gfx.SmoothingMode = SmoothingMode.AntiAlias;
            gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

            //add noise
            if (noisy)
            {
                int i, r, x, y;
                var pen = new Pen(Color.Yellow);
                for (i = 1; i < 10; i++)
                {
                    pen.Color = Color.FromArgb(
                    (rand.Next(0, 255)),
                    (rand.Next(0, 255)),
                    (rand.Next(0, 255)));

                    r = rand.Next(0, (130 / 3));
                    x = rand.Next(0, 130);
                    y = rand.Next(0, 30);

                    gfx.DrawEllipse(pen, x - r, y - r, r, r);
                }
            }

            //add question
            gfx.DrawString(captcha, new Font("Tahoma", 15), Brushes.Gray, 2, 3);

            //render as Jpeg
            bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);

            img = this.File(mem.GetBuffer(), "image/Jpeg");

        }
        return img;
    }

和我的行动:

<img alt="Captcha" src="@Url.Action("CaptchaImageComm", "DataCaptcha")" style="" />

我设置缓存设置如下:

filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1))‌​;
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.A‌​llCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCach‌​e);
filterContext.HttpContext.Response.Cache.SetNoStore();
4

1 回答 1

1

也许另一种方法是在当前日期时间中包含时间戳参数以避免缓存。这种技术有时用于防止在浏览器中缓存网页,也许可以在这里使用。只是一个想法。

于 2013-06-17T15:35:49.900 回答