浅谈3次登录错误

总体的 逻辑思路如下图.(右上角为数据库字段,我的表名是T_UsersLogIn)

此文是在5分钟内,不能超过3次错误。

 

源代码 下载 http://pan.baidu.com/s/1nv8W6UH

 

 

 

 

实体模型,就用数据库生成的。(为什么放入Models 目录下不可以更新,机器问题?)

 

 

 

新建一个 视图类 ,用于登录。

 

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace ThreeLogIn.Models.ViewModel
{
    public class LogInModel
    {
        [DisplayName("用户名")]
        [Required(ErrorMessage = "请输入用户名")]
        public string userName { get; set; }

        [DisplayName("密码")]
        [Required(ErrorMessage = "请输入密码")]
        [StringLength(50, MinimumLength = 5, ErrorMessage = "密码应该在5到50位之间")]
        public string userPwd { get; set; }
    }
}

 

 

在web.config 的 appSettings 内写好要 时间段与错误次数

<appSettings>
//.......
    <add key="LoginBetweenTime" value="5" /><!--可允许时间段内的错误次数 ,以分钟为单位-->
    <add key="LoginErrorTime" value="3" /><!--可允许的错误次数-->

  </appSettings>

 

打算用 Ajax 无刷新 登录 ,定义了一个返回消息的 格式

 

namespace ThreeLogIn.Models
{
    public class AjaxMsgModel
    {
        public string Msg { get; set; } //错误信息
        public string Status { get; set; } //状态
        public string BackUrl { get; set; } 
        public object Data { get; set; } //数据
    } 
}

 

 

Status 的种类,放入到另一个枚举中

 

namespace ThreeLogIn.Models
{
    public class MsgStatus
    {
        public enum STATUS
        {
            ok = 0,
            err = 1,
            other = 2,
        };
    }
}

 

 

添加一个 Home控制器,写入Action方法

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using ThreeLogIn.Models;

namespace ThreeLogIn.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index() //登录成功后跳转到此
        {
            return View();
        }

        [HttpGet]
        public ActionResult LogIn() //默认加载
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogIn(Models.ViewModel.LogInModel user) //登录认证
        {
            if (!ModelState.IsValid)
            {
                return Content("请勿禁用浏览器脚本!");
            }
            AjaxMsgModel data = new AjaxMsgModel(); //返回信息
            Small_OAEntities db = new Small_OAEntities();

            T_UsersLogIn[] results =
                (from u in db.T_UsersLogIn where u.UserName == user.userName && u.IsDelete == false select u).ToArray();
            if (results.Count() <= 0)
            {
                data.Data = ("用户" + user.userName + "不存在");
                return Json(data);
            }

            if (results.Count() > 1)
            {
                data.Data = ("该用存在重名");
            }
            else
            {
                int LoginBetweenTime =
                    Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LoginBetweenTime"]);
                int LoginErrorTime =
                    Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LoginErrorTime"]);

                T_UsersLogIn userLogin = db.T_UsersLogIn.Where(u => u.UserName == user.userName).FirstOrDefault();
                    //先查找出要修改的对象
                TimeSpan ts = DateTime.Now - results[0].LastErrorTime; //计算时间差
                double mins = ts.TotalMinutes;
                userLogin.LastErrorTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));


                // 超出时间
                if (mins >= LoginBetweenTime) //可允许时间段内的错误次数
                {
                    if (user.userPwd == results[0].UserPwd.ToString())
                    {
                        userLogin.ErrorTime = 0; //修改数据
                        db.SaveChanges();
                        data.Status = MsgStatus.STATUS.ok.ToString();
                        data.BackUrl = "Index";
                        return Json(data);
                    }
                    else
                    {
                        userLogin.ErrorTime = 1; //修改数据
                        db.SaveChanges();
                        data.Data = ("您已连续输入 " + userLogin.ErrorTime + " 次错误!");
                    }
                }
                else
                {
                    //未超出时间
                    if (results[0].ErrorTime < LoginErrorTime)
                    {
                        if (user.userPwd == results[0].UserPwd.ToString())
                        {
                            userLogin.ErrorTime = 0; //修改数据
                            db.SaveChanges();
                            data.Status = MsgStatus.STATUS.ok.ToString();
                            data.BackUrl = "Index";
                            return Json(data);
                        }
                        else
                        {
                            userLogin.ErrorTime = results[0].ErrorTime + 1; //修改数据
                            db.SaveChanges();
                            data.Data = ("您已连续输入 " + userLogin.ErrorTime + " 次错误!");
                        }

                    }
                    else
                    {
                        data.Data = ("连续输出次数过多," + "请过" + LoginBetweenTime + "分钟后再尝试登录.");
                    }

                }
                return Json(data);

               
            }
            return View();
        }

    }
}

 

 

 

导入js 文件(/View/Shared/_Layout.cshtml)  //我是在模板中导入的

1.jquery-1.8.2.min.js

2.jquery.validate.min.js

3.jquery.validate.unobtrusive.min.js

4. jquery.unobtrusive-ajax.min.js

 

 

然后去写 登录视图  LogIn.cshtml

@{
    ViewBag.Title = "LogIn";
}
@model ThreeLogIn.Models.ViewModel.LogInModel

<h2>用户登录</h2>
<script type="text/javascript">
    function onSuccess(data) {
        if (data.Status ==="ok") {
            window.location.href=data.BackUrl;
        } else {
            if (data.Data !=null) {
                alert(data.Data);
            }
        }
    }
</script>

@using (Ajax.BeginForm("LogIn", "Home", new AjaxOptions()
{
    Confirm = "您是否要提交",
    HttpMethod = "Post",
    InsertionMode = InsertionMode.Replace,
   // UpdateTargetId = "result",  //返回内容显示到此处
    OnSuccess = "onSuccess",
    LoadingElementId = "imgLoad"
}))
{
    <table id="LogInUser" name="LogInUser">
        <tr>
            <td>用户名</td>
            <td>@Html.TextBoxFor(u => u.userName, new { style = "border: 1px solid #0094ff" })</td>
            <td>@Html.ValidationMessageFor(u => u.userName)</td>
        </tr>
        <tr>
            <td>密码</td>
            <td>@Html.PasswordFor(u => u.userPwd, new { style = "border: 1px solid #0094ff" })</td>
            <td>@Html.ValidationMessageFor(u => u.userPwd)</td>
        </tr>
    </table>
    <input type="submit" value="登录" />
    <div id="result"></div>
    <div id="imgLoad" style="display: none">
        正在加载...
    </div>
}

 

 

结果 如下

 

 

 

 

 

 

posted @ 2017-01-22 17:58  likehc  阅读(735)  评论(0编辑  收藏  举报