登录整体思路是:生成的验证码存入session中,然后与提交表单中中输入的验证码作比较。
登陆成功:存入浏览器的cookie中。
注销:清楚浏览器中存入的登录名。
1.验证码页面html
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div class="login_position">
<p class="center_text p1 top30_M">xx平台管理</p>
<div class="hr1"></div>
<div class="left50_M">
<div class="login_input top15_M">
<img src="~/Content/images/login_person.png" /><input type="text" name="username" autocomplete="off" id="username" placeholder="请输入用户名" />
</div>
<div class="login_input top30_M">
<img src="~/Content/images/login_lock.png" /><input type="password" name="password" placeholder="请输入密码"/>
</div>
<div class="top30_M">
<input placeholder="验证码" name="code" autocomplete="off" id="code" class="login_input2" style="width:100px;" />
<img class="left15_M" onclick="this.src = this.src + '?' + Math.random();" src="@Url.Action("code","Account")" title="看不清楚,换一张" width="83" height="29" align="absmiddle" style="cursor: pointer;" id="imgcodeaa" />
</div>
<input type="submit" value="登 录" class="login_btn top30_M" />
</div>
</div>
}
2.控制器
验证码生成代码
//验证码入口
[AllowAnonymous]
public ActionResult Code()
{
return File(AccountController.CreateCheckIamge(), @"iamge/Jpeg");
}
//验证码生成并且存入服务器session
private static string GenerateCheckCode()
{
try
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
//Session["CheckCode"] = checkCode;
System.Web.HttpContext.Current.Session.Add("CheckCode", checkCode.ToLower());
//Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
return checkCode;
}
catch (Exception ex)
{
return "";
}
}
//添加水印
private static byte[] CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return null;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x