62,046
社区成员
发帖
与我相关
我的任务
分享
public class ValidateCodeController : Controller
{
//
// GET: /ValidateCode/
public ActionResult Index()
{
return View();
}
public ActionResult GetValidateCode()
{
string checkCode = GetRandomCode(4);
Session["CheckCode"] = checkCode;
return File(CreateImage(checkCode), @"image/Jpeg");
}
private string GetRandomCode(int CodeCount)
{
...... 此处省略
return RandomCode;
}
private byte[] CreateImage(string checkCode)
{
......省略
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
//history back 不重复
Response.Cache.SetNoStore();//这一句
Response.ClearContent();
//Response.ContentType = "image/Jpeg";
//Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
return ms.ToArray();
}
}
public class ValidateCodeController : Controller
{
//
// GET: /ValidateCode/
public ActionResult Index()
{
return View();
}
public ActionResult GetValidateCode()
{
string checkCode = GetRandomCode(4);
Session["CheckCode"] = checkCode;
Response.Cache.SetNoStore();//这一句
Response.ClearContent();
return File(CreateImage(checkCode), @"image/Jpeg");
}
private string GetRandomCode(int CodeCount)
{
return "111";
}
private byte[] CreateImage(string checkCode)
{
using (Bitmap bmpOut = new Bitmap(200, 50))
{
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.Black, 0, 0, 200, 50);
g.DrawString(checkCode, new Font("Verdana", 18), new SolidBrush(Color.White), 0, 0);
using (MemoryStream ms = new MemoryStream())
{
bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] bmpBytes = ms.GetBuffer();
return bmpBytes;
}
}
}
}
使用部分,在index.aspx中加入
<asp:Image ID="Image1" runat="server" ImageUrl="/ValidateCode/GetValidateCode" />
注意这里加入了 /根节点,因为我的index.aspx在/views/home下,不加 /的话就是相对路径,会去找 /Views/Home/ValidateCode/GetValidateCode 这个路径,是红叉叉。