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獲取地址的這個也是在網上查找的。

然后就可以去登錄了。調試結果如下

好了登錄頁面就這樣了。可能中間講的很亂。有疑問的或者有覺得不好的請指出來哈。

百度源碼下載地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM