MVC 验证码
1、新建一个 code.cs
2、/获取验证码
public string Number()
{
string[] str = new string[24]
{ "a","b","c","d","e","f","j","h","i","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z"};
Random rand = new Random();
string s = null;
for (int i = 0; i <= 3; i++)
{
int t = rand.Next(1,24);
s += str[t]+" ";
}
return s;
}
//LZ技术不精 注释可能有误 欢迎更改
3、 public byte[] Images(HttpContextBase context) {
Bitmap image = new Bitmap(100,30);//定义一个图片框架(width:100 height:30)
Graphics g = Graphics.FromImage(image);
try
{
Font f = new Font("Arial", 20, FontStyle.Italic);//初始化一个斜体为20的字体
Brush b = new SolidBrush(Color.Black);
g.Clear(Color.White);
g.DrawString(Number(), f, b, 3, 3);//在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。
Pen p = new Pen(Color.Red,0.5f);//初始化一个红颜色的钢笔 钢笔宽度0.5
Random rd = new Random();
for (int i = 0; i < 5; i++)
{
int y = rd.Next(image.Height);//根据图片高度生成一个随机数
g.DrawLine(p, 0, y, image.Width, y);//根据坐标画5条红色的线
}
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);//把图片保存在内存流中
return ms.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
这里返回的是2进制 下面 修改 controller
code c = new code();
public ActionResult Index()
{
return View();
}
public FileContentResult ima() //FileContentResult 将2进制内容发送到相应
{
byte[] b = c.Images(this.HttpContext);
return File(b, @"image/jpg");
}
下面看看view
<td>@Html.Label("验证码"):</td>
<td >@Html.TextBox("yan", "", new { style = "width:70px" })
<span >
<img id="imgcode" src="@Url.RouteUrl("Default", new { controller = "MemberShip", action = "ima" })" onclick="CodeChange()" /></span> //RouteUrl 这个URL返回 \MemberShip\ima
</td>
效果