Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理4

 首先先加个区域,名为Admin

using System.Web.Mvc;

namespace AuthorDesign.Web.Areas.Admin {
    public class AdminAreaRegistration : AreaRegistration {
        public override string AreaName {
            get {
                return "Admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
View Code

更改下区域里面里的路由配置代码为:

using System.Web.Mvc;

namespace AuthorDesign.Web.Areas.Admin {
    public class AdminAreaRegistration : AreaRegistration {
        public override string AreaName {
            get {
                return "Admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { controller= "Home", action = "Index", id = UrlParameter.Optional },
                new string[] { "AuthorDesign.Web.Areas.Admin.Controllers" }
            );
        }
    }
}
View Code

然后再区域下的Controllers文件下添加一个名为Account的控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AuthorDesign.Web.Areas.Admin.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Admin/Account/

        public ActionResult Index()
        {
            return View();
        }

    }
}
View Code

将Index改为Login

然后我再添加Login的视图。点击添加之后就会在对应的Views。

页面模板就是找bootstrap的模板了。http://pan.baidu.com/s/1mgs7hWG这里是分享的模板链接。

首先是登录页面的html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>权限管理后台-登陆</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!-- basic styles -->

    <link href="/Content/assets/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="/Content/assets/css/font-awesome.min.css" />

    <!--[if IE 7]>
      <link rel="stylesheet" href="/Content/assets/css/font-awesome-ie7.min.css" />
    <![endif]-->
    <!-- page specific plugin styles -->
    <!-- fonts -->

    <!-- ace styles -->

    <link rel="stylesheet" href="/Content/assets/css/ace.min.css" />
    <link rel="stylesheet" href="/Content/assets/css/ace-rtl.min.css" />

    <!--[if lte IE 8]>
      <link rel="stylesheet" href="/Content/assets/css/ace-ie.min.css" />
    <![endif]-->
    <!-- inline styles related to this page -->
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="/Content/assets/js/html5shiv.js"></script>
    <script src="/Content/assets/js/respond.min.js"></script>
    <![endif]-->
</head>

<body class="login-layout">
    <div class="main-container">
        <div class="main-content">
            <div class="row">
                <div class="col-sm-10 col-sm-offset-1">
                    <div class="login-container">
                        <div class="center">
                            <h1>
                                <i class="icon-leaf green"></i>
                                <span class="red">权限</span>
                                <span class="white">管理后台</span>
                            </h1>
                            <h4 class="blue">&copy; yjq/h4>
                        </div>

                        <div class="space-6"></div>

                        <div class="position-relative">
                            <div id="login-box" class="login-box visible widget-box no-border">
                                <div class="widget-body">
                                    <div class="widget-main">
                                        <h4 class="header blue lighter bigger">
                                            <i class="icon-coffee green"></i>
                                            请输入您的用户名和密码
                                        </h4>

                                        <div class="space-6"></div>

                                        <form>
                                            <fieldset>
                                                <label class="block clearfix">
                                                    <span class="block input-icon input-icon-right">
                                                        <input type="text" class="form-control" placeholder="用户名" />
                                                        <i class="icon-user"></i>
                                                    </span>
                                                </label>

                                                <label class="block clearfix">
                                                    <span class="block input-icon input-icon-right">
                                                        <input type="password" class="form-control" placeholder="密码" />
                                                        <i class="icon-lock"></i>
                                                    </span>
                                                </label>
                                                <label class="block clearfix">
                                                    <span class="block input-icon input-icon-right">
                                                        <input type="text" class="col-xs-10 col-sm-5" style="height:34px;" placeholder="6位数的验证码" /><img src="/Admin/account/ValidateImg" id="validimg" height="34" alt="验证码" title="看不清?,换一张" style="cursor:pointer;" onclick="ShowValidate()" />
                                                        <i class="icon-lock"></i>
                                                    </span>
                                                </label>
                                                <div class="space"></div>

                                                <div class="clearfix">
                                                    <label class="inline">
                                                        <input type="checkbox" class="ace" />
                                                        <span class="lbl"> 记住密码</span>
                                                    </label>

                                                    <button type="button" class="width-35 pull-right btn btn-sm btn-primary">
                                                        <i class="icon-key"></i>
                                                        登录
                                                    </button>
                                                </div>

                                                <div class="space-4"></div>
                                            </fieldset>
                                        </form>
                                    </div><!-- /widget-main -->
                                </div><!-- /widget-body -->
                            </div><!-- /login-box -->
                        </div><!-- /position-relative -->
                    </div>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div>
    </div><!-- /.main-container -->
    <!-- basic scripts -->
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        window.jQuery || document.write("<script src='/Content/assets/js/jquery-2.0.3.min.js'>" + "<" + "/script>");
    </script>

    <!-- <![endif]-->
    <!--[if IE]>
    <script type="text/javascript">
     window.jQuery || document.write("<script src='/Content/assets/js/jquery-1.10.2.min.js'>"+"<"+"/script>");
    </script>
    <![endif]-->

    <script type="text/javascript">
        if ("ontouchend" in document) document.write("<script src='/Content/assets/js/jquery.mobile.custom.min.js'>" + "<" + "/script>");
    </script>

    <!-- inline scripts related to this page -->

    <script type="text/javascript">
        function show_box(id) {
            jQuery('.widget-box.visible').removeClass('visible');
            jQuery('#' + id).addClass('visible');
        }
        function ShowValidate() {
            $("#validimg").get(0).src = '/Admin/Account/ValidateImg?time=' + (new Date()).getTime();
        }
    </script>
</body>
</html>
View Code

效果如下

验证码的代码如下:

#region 验证码
        /// <summary>
        /// 功能:返回验证码图片
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidateImg() {
            Color color1 = new Color();
            //---------产生随机6位字符串
            Random ran = new Random();
            char[] c = new char[62];
            char[] ou = new char[6];
            int n = 0;
            for (int i = 65; i < 91; i++) {
                c[n] = (char)i;
                n++;
            }
            for (int j = 97; j < 123; j++) {
                c[n] = (char)j;
                n++;
            }
            for (int k = 48; k < 58; k++) {
                c[n] = (char)k;
                n++;
            }
            foreach (char ch in c) {
                Console.WriteLine(ch);
            }
            string outcode = "";
            for (int h = 0; h < 6; h++) {
                ou[h] = c[ran.Next(62)];
                outcode += ou[h].ToString();
            }
            //
            Session["ValidateImgCode"] = outcode;

            //1.创建一个新的图片,大小为(输入的字符串的长度*12),22
            System.Drawing.Bitmap bmap = new System.Drawing.Bitmap(outcode.Length * 18, 25);

            //2.定义画图面板,基于创建的新图片来创建
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmap);

            //3.由于默认的画图面板背景是黑色,所有使用clear方法把背景清除,同时把背景颜色设置为白色
            g.Clear(System.Drawing.Color.White);

            // 画图片的背景噪音线
            for (int i = 0; i < 25; i++) {
                int x1 = ran.Next(bmap.Width);
                int x2 = ran.Next(bmap.Width);
                int y1 = ran.Next(bmap.Height);
                int y2 = ran.Next(bmap.Height);
                g.DrawLine(new Pen(color1), x1, y1, x2, y2);
            }

            // 画图片的前景噪音线
            for (int i = 0; i < 100; i++) {
                int x = ran.Next(bmap.Width);
                int y = ran.Next(bmap.Height);
                bmap.SetPixel(x, y, Color.FromArgb(ran.Next()));
            }

            //4.使用DrawString 方法把要输出的字符串输出到画板上。输出的字符从参数(outcode)内获得。
            Font font = new Font("Arial", 14, FontStyle.Bold | FontStyle.Italic);
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bmap.Width, bmap.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(outcode, font, brush, 0, 0);

            //5.定义一个内存流,把新创建的图片保存到内存流内,这样就不用保存到磁盘上,提高了速度。
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            //6.把新创建的图片保存到内存流中,格式为jpeg的类型
            bmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            //7.输出这张图片,由于此页面的 ContentType="image/jpeg" 所以会输出图片到客户端。同时输出是以字节输出,所以要把内存流转换为字节序列,使用ToArray()方法。
            Response.BinaryWrite(ms.ToArray());
            return View();
        }
        #endregion
View Code

注意验证码要建个个分布视图用来输出图片用的。

然后再Model文件夹下建立LoginModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AuthorDesign.Web.Areas.Admin.Models {
    /// <summary>
    /// 登录类
    /// </summary>
    public class LoginModel {
        /// <summary>
        /// 用户名
        /// </summary>
        [Required(ErrorMessage="请输入用户名")]
        [StringLength(30,MinimumLength=5,ErrorMessage="请输入正确的用户名")]
        public string UserName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        [Required(ErrorMessage = "请输入用密码")]
        [StringLength(30, MinimumLength = 5, ErrorMessage = "请输入正确的密码")]
        public string Password { get; set; }
        /// <summary>
        /// 验证码
        /// </summary>
        [Required(ErrorMessage="请输入验证码")]
        [StringLength(6,MinimumLength=6,ErrorMessage="验证码错误")]
        public string ValidateCode { get; set; }
        /// <summary>
        /// 是否记住密码
        /// </summary>
        public bool IsRemind { get; set; }
    }
}
View Code

然后更改登录页面的Html代码

@model AuthorDesign.Web.Areas.Admin.Models.LoginModel
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>权限管理后台-登陆</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <!-- basic styles -->

    <link href="/Content/assets/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="/Content/assets/css/font-awesome.min.css" />

    <!--[if IE 7]>
      <link rel="stylesheet" href="/Content/assets/css/font-awesome-ie7.min.css" />
    <![endif]-->
    <!-- page specific plugin styles -->
    <!-- fonts -->
    <!-- ace styles -->

    <link rel="stylesheet" href="/Content/assets/css/ace.min.css" />
    <link rel="stylesheet" href="/Content/assets/css/ace-rtl.min.css" />

    <!--[if lte IE 8]>
      <link rel="stylesheet" href="/Content/assets/css/ace-ie.min.css" />
    <![endif]-->
    <!-- inline styles related to this page -->
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="/Content/assets/js/html5shiv.js"></script>
    <script src="/Content/assets/js/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
        .field-validation-error {
            color: red;
        }
    </style>
</head>

<body class="login-layout">
    <div class="main-container">
        <div class="main-content">
            <div class="row">
                <div class="col-sm-10 col-sm-offset-1">
                    <div class="login-container">
                        <div class="center">
                            <h1>
                                <i class="icon-leaf green"></i>
                                <span class="red">权限</span>
                                <span class="white">管理后台</span>
                            </h1>
                            <h4 class="blue">&copy; yjq</h4>
                        </div>

                        <div class="space-6"></div>

                        <div class="position-relative">
                            <div id="login-box" class="login-box visible widget-box no-border">
                                <div class="widget-body">
                                    <div class="widget-main">
                                        <h4 class="header blue lighter bigger">
                                            <i class="icon-coffee green"></i>
                                            请输入您的用户名和密码
                                        </h4>
                                        <form id="LoginForm">
                                            <div class="space-6"></div>
                                            <fieldset>
                                                <label class="block clearfix">
                                                    <span class="block input-icon input-icon-right">
                                                        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", @placeholder = "用户名" })
                                                        <i class="icon-user"></i>
                                                    </span>
                                                    <span>
                                                        @Html.ValidationMessageFor(m => m.UserName)
                                                    </span>
                                                </label>

                                                <label class="block clearfix">
                                                    <span class="block input-icon input-icon-right">
                                                        @Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "密码" })
                                                        <i class="icon-lock"></i>
                                                    </span>
                                                    <span>
                                                        @Html.ValidationMessageFor(m => m.Password)
                                                    </span>
                                                </label>
                                                <label class="block clearfix">
                                                    <span class="block input-icon input-icon-right">
                                                        @Html.TextBoxFor(m => m.ValidateCode, new { @class = "col-xs-10 col-sm-5", @style = "height:34px;", @placeholder = "6位数的验证码" })<img src="/Admin/account/ValidateImg" id="validimg" height="34" alt="验证码" title="看不清?,换一张" style="cursor:pointer;" onclick="ShowValidate()" />
                                                        <i class="con-inbox"></i>
                                                    </span>
                                                    <span>
                                                        @Html.ValidationMessageFor(m => m.ValidateCode)
                                                    </span>
                                                </label>
                                                <div class="space"></div>

                                                <div class="clearfix">
                                                    <label class="inline">
                                                        <input type="checkbox" name="IsRemind" id="IsRemind" class="ace" value="false" />
                                                        <span class="lbl"> 记住密码</span>
                                                    </label>

                                                    <button type="submit" class="width-35 pull-right btn btn-sm btn-primary">
                                                        <i class="icon-key"></i>
                                                        登录
                                                    </button>
                                                </div>

                                                <div class="space-4"></div>
                                            </fieldset>
                                        </form>
                                    </div><!-- /widget-main -->
                                </div><!-- /widget-body -->
                            </div><!-- /login-box -->
                        </div><!-- /position-relative -->
                    </div>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div>
    </div><!-- /.main-container -->
    <!-- basic scripts -->
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    <script type="text/javascript">
        window.jQuery || document.write("<script src='/Content/assets/js/jquery-2.0.3.min.js'>" + "<" + "/script>");
    </script>

    <!-- <![endif]-->
    <!--[if IE]>
    <script type="text/javascript">
     window.jQuery || document.write("<script src='/Content/assets/js/jquery-1.10.2.min.js'>"+"<"+"/script>");
    </script>
    <![endif]-->

    <script type="text/javascript">
        if ("ontouchend" in document) document.write("<script src='/Content/assets/js/jquery.mobile.custom.min.js'>" + "<" + "/script>");
    </script>

    <!-- inline scripts related to this page -->
    <script src="~/Content/assets/js/bootstrap.min.js"></script>
    <script src="/Content/assets/js/bootbox.min.js"></script>
    <script type="text/javascript">
        function show_box(id) {
            jQuery('.widget-box.visible').removeClass('visible');
            jQuery('#' + id).addClass('visible');
        }
        function ShowValidate() {
            $("#validimg").get(0).src = '/Admin/Account/ValidateImg?time=' + (new Date()).getTime();
        }
        $("#LoginForm").submit(function () {
            if ($("#LoginForm").valid()) {
                if ($("#IsRemind").is(":checked")) {
                    $("#IsRemind").val(true);
                } else {
                    $("#IsRemind").val(false);
                }
                $.ajax({
                    type: "post",
                    url: "/Admin/Account/Login",
                    data: $("#LoginForm").serialize(),
                    success: function (result) {
                        if (result.state == "success") {
                            alert("登录成功了!");
                        } else {
                            bootbox.alert({
                                buttons: {
                                    ok: {
                                        label: '我知道了',
                                        className: 'btn btn-primary'
                                    }
                                }, callback: function () {
                                },
                                message:result.message
                            });
                        }
                    }
                })
                return false;
            } else {
                return false;
            }
        })
    </script>

</body>
</html>
View Code

 

然后再建立一个类,这个类是专门用来与数据层进行交互的。

using AuthorDesign.DAL;
using AuthorDesign.IDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Web;

namespace AuthorDesign.Web.App_Start.Common {
    public class EnterRepository {
        /// <summary>
        /// 获取DAL入口类
        /// </summary>
        /// <returns></returns>
        public static IRepositoryEnter GetRepositoryEnter() {
            IRepositoryEnter _enter = CallContext.GetData("CurrentRepositoryEnter") as RepositoryEnter;
            if (_enter == null) {
                _enter = new RepositoryEnter();
                CallContext.SetData("CurrentRepositoryEnter", _enter);
            }
            return _enter;
        }
    }
}
View Code

在后台添加登录的方法:

在写方法的时候我发现Admin这个类少了个是否可登录这字段,那么就先去加上这个字段

/// <summary>
/// 是否可登录
/// </summary>
public Byte IsLogin { get; set; }

然后在这个类中添加如下代码:

        protected override void Seed(AuthorDesign.DAL.AuthorDesignContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            context.Admins.AddOrUpdate(
                  p => p.AdminName,
                  new Admin() { AdminName = "admin", CreateTime = DateTime.Now, IsLogin = 1, Salt = "1234567890", Password = "42C224B3C8899047460F5A6D1C041411", LastLoginAddress = "大中国", LastLoginIp = "192.168.254.23", LastLoginTime = DateTime.Now, IsSuperAdmin = 1 }
            );
            //
        }
View Code

这个的作用就是像数据库中加入一条数据,我这条加入的数据是一个用户名为admin 密码为123456的数据

然后执行控制台指令 add-migration AddAdminIsLogin  执行完成之后再执行 update-database 数据库就更新了,然后admin的这条默认数据也加进去了。

然我在写这个方法的是去DAL中把原先的增删改的方法修改了下,

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace AuthorDesign.DAL {
    public class BaseRepository<T> where T : class,new() {

        public DbContext db = DbContextFactory.GetCurrentDbContext();

        /// <summary>
        /// 添加一条记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T AddEntity(T entity) {
            db.Entry<T>(entity).State = EntityState.Added;
            //db.SaveChanges();
            return entity;
        }
        /// <summary>
        /// 修改一条记录
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="property">需要修改的字段名称</param>
        /// <returns></returns>
        public bool EditEntity(T entity, string[] property) {
            DbEntityEntry<T> entry = db.Entry<T>(entity);
            entry.State = EntityState.Unchanged;
            foreach (var item in property) {
                entry.Property(item).IsModified = true;
            }
            //return db.SaveChanges() > 0;
            return true;
        }
        /// <summary>
        /// 删除一条记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool DeleteEntity(T entity) {
            DbEntityEntry<T> entry = db.Entry<T>(entity);
            entry.State = EntityState.Deleted;
            //return db.SaveChanges() > 0;
             return true;
        }
        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> LoadEntities() {
            return db.Set<T>();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="whereLamda">查询条件</param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities(Expression<Func<T, bool>> whereLamda) {
            return db.Set<T>().Where<T>(whereLamda);
        }
        /// <summary>
        /// 对查询结果进行升序排序
        /// </summary>
        /// <typeparam name="S">排序字段类型</typeparam>
        /// <param name="queryable">查询结果</param>
        /// <param name="orderLamda">排序表达式</param>
        /// <returns>根据排序条件排序好之后的排序结果</returns>
        public IOrderedQueryable<T> Order<S>(IQueryable<T> queryable, Expression<Func<T, S>> orderLamda) {
            return queryable.OrderBy(orderLamda);
        }
        /// <summary>
        /// 对排序结果再次进行升序排序
        /// </summary>
        /// <typeparam name="S">排序字段类型</typeparam>
        /// <param name="queryable">根据排序条件排序好之后的排序结果</param>
        /// <param name="orderLamda">排序表达式</param>
        /// <returns>根据排序条件排序好之后的排序结果</returns>
        public IOrderedQueryable<T> ThenOrder<S>(IOrderedQueryable<T> queryable, Expression<Func<T, S>> orderLamda) {
            return queryable.ThenBy(orderLamda);
        }
        /// <summary>
        /// 对查询结果进行降序排序
        /// </summary>
        /// <typeparam name="S">排序字段类型</typeparam>
        /// <param name="queryable">查询结果</param>
        /// <param name="orderLamda">排序表达式</param>
        /// <returns>根据排序条件排序好之后的排序结果</returns>
        public IOrderedQueryable<T> OrderDesc<S>(IQueryable<T> queryable, Expression<Func<T, S>> orderLamda) {
            return queryable.OrderByDescending(orderLamda);
        }
        /// <summary>
        /// 对排序结果再次进行降序排序
        /// </summary>
        /// <typeparam name="S">排序字段类型</typeparam>
        /// <param name="queryable">根据排序条件排序好之后的排序结果</param>
        /// <param name="orderLamda">排序表达式</param>
        /// <returns>根据排序条件排序好之后的排序结果</returns>
        public IOrderedQueryable<T> ThenOrderDesc<S>(IOrderedQueryable<T> queryable, Expression<Func<T, S>> orderLamda) {
            return queryable.ThenByDescending(orderLamda);
        }
        /// <summary>
        /// 对排序结果进行分页操作
        /// </summary>
        /// <param name="queryable">根据排序条件排序好之后的排序结果</param>
        /// <param name="nowNum">跳过序列中指定数量的元素</param>
        /// <param name="pageSize">从序列的开头返回指定数量的连续元素</param>
        /// <returns>指定长度的列表</returns>
        public IQueryable<T> LoadPageEnties(IOrderedQueryable<T> queryable, int nowNum, int pageSize) {
            return queryable.Skip<T>(nowNum + 1).Take<T>(pageSize);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="S">排序类型</typeparam>
        /// <param name="whereLamda">查询条件</param>
        /// <param name="orderLamda">排序条件</param>
        /// <param name="isDesc">是否倒序</param>
        /// <param name="pageIndex">第几页</param>
        /// <param name="pageSize">页长</param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities<S>(Expression<Func<T, bool>> whereLamda, Expression<Func<T, S>> orderLamda, bool isDesc, int pageIndex, int pageSize, out int rowCount) {
            var temp = db.Set<T>().Where<T>(whereLamda);
            rowCount = temp.Count();
            if (isDesc)
                temp = temp.OrderByDescending<T, S>(orderLamda).Skip<T>(pageSize * (pageIndex - 1) + 1).Take<T>(pageSize);
            else
                temp = temp.OrderBy<T, S>(orderLamda).Skip<T>(pageSize * (pageIndex - 1) + 1).Take<T>(pageSize);
            return temp;
        }
    }
}
View Code

我把savechange的方法都注释掉了,因为我把这方法都放到web层来操作了。在ef中增删改方法只有在调用savechange方法之后他才会和数据库进行交互的。把savechange方法提出来有利于控制。

然后再Account控制器下面添加一个登录的方法。

        [HttpPost]
        public JsonResult Login(Models.LoginModel model) {
            if (ModelState.IsValid) {
                //首先判断下验证码是否正确
                if (Session["ValidateImgCode"] != null && string.Equals(Session["ValidateImgCode"].ToString(),
                    model.ValidateCode, StringComparison.OrdinalIgnoreCase)) {
                    Model.Admin adminModel = new Model.Admin();
                    if (new Regex("1[3|5|7|8|][0-9]{9}").IsMatch(model.UserName)) {//匹配手机号码
                        adminModel = EnterRepository.GetRepositoryEnter().GetAdminRepository.LoadEntities(m => m.Mobile == model.UserName && m.IsLogin == 1).FirstOrDefault();
                    }
                    else if (new Regex(@"[A-Za-z0-9.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}").IsMatch(model.UserName)) {//匹配邮箱
                        adminModel = EnterRepository.GetRepositoryEnter().GetAdminRepository.LoadEntities(m => m.Email == model.UserName && m.IsLogin == 1).FirstOrDefault();
                    }
                    else {//匹配用户名
                        adminModel = EnterRepository.GetRepositoryEnter().GetAdminRepository.LoadEntities(m => m.AdminName == model.UserName&&m.IsLogin==1).FirstOrDefault();
                    }
                    if (adminModel == null) {
                        return Json(new {
                            state = "error",
                            message = "用户名不存在"
                        });
                    }
                    else {
                        //判断密码是否正确
                        if (adminModel.Password == MD5Helper.CreatePasswordMd5(model.Password, adminModel.Salt)) {
                            adminModel.LastLoginTime = DateTime.Now;
                            adminModel.LastLoginIp = IpHelper.GetRealIP();
                            adminModel.LastLoginAddress = IpHelper.GetAdrByIp(adminModel.LastLoginIp);
                            adminModel.LastLoginInfo = IpHelper.GetBrowerVersion();
                            //添加登录日志并修改上次登录信息
                            EnterRepository.GetRepositoryEnter().GetAdminLoginLogRepository.AddEntity(new Model.AdminLoginLog() {
                                AdminId = adminModel.Id,
                                AdminLoginAddress = adminModel.LastLoginAddress,
                                AdminLoginIP = adminModel.LastLoginIp,
                                AdminLoginTime = adminModel.LastLoginTime,
                                AdminLoginInfo = adminModel.LastLoginInfo
                            });
                            if (EnterRepository.GetRepositoryEnter().SaveChange() > 0) {
                                //登录成功,保存cookie
                                WebCookieHelper.SetCookie(adminModel.Id, model.UserName, adminModel.LastLoginTime, adminModel.LastLoginIp, adminModel.LastLoginAddress, adminModel.IsSuperAdmin, adminModel.AuthoryId, (model.IsRemind!=null&&model.IsRemind )? 15 : 0);
                                return Json(new {
                                    state = "success",
                                    message = "登录成功"
                                });
                            }
                            else {
                                return Json(new {
                                    state = "success",
                                    message = "服务器泡妞去了"
                                });
                            }
                        }
                        else {
                            return Json(new {
                                state = "error",
                                message = "密码错误"
                            });
                        }
                    }
                }
                else {
                    return Json(new {
                        state = "error",
                        message = "验证码错误"
                    });
                }
            }
            else {
                return Json(new {
                    state = "error",
                    message = "输入信息不完整"
                });
            }
        }
View Code
 

这里在登录的时候使用了cookie来存储信息,和加入了一条用户登录日志。对于cookie的存储,我会放源码到百度云分享去的,昨天看了下github好像出了点问题。

获取用户的登录Ip和浏览器信息的之类的都是在网上查到的,根据ip获取地址的这个也是在网上查找的。

然后就可以去登录了。调试结果如下

好了登录页面就这样了。可能中间讲的很乱。有疑问的或者有觉得不好的请指出来哈。

百度源码下载地址

posted @ 2015-11-23 23:31  yjq_net  阅读(3873)  评论(3编辑  收藏  举报