资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

三、Asp.NetMVC4.0开发CMS系统案例之用户登录模块开发-创新互联

   本次开发是将三层架构与MVC结合一起来,我们看下面一个系统结构:

创新互联是一家专注于成都网站制作、成都网站建设与策划设计,庆元网站建设哪家好?创新互联做网站,专注于网站建设10年,网设计领域的专业建站公司;建站业务涵盖:庆元等地区。庆元做网站价格咨询:18980820575

   View ->Contraller->Model->BLL->DAL->SQLSERVER

            |        |        |

            ----------->Extensions----->FrameWork

            |

            __>Common

   Extensions包括扩展类功能,例如控件的再重新,权限的重新验证等。Common是一些公共×××。

   第一步:创建用户登录模型,可以与注册模型类(SysComUerRegister),用户模型(SysComUser)写入同一个文件中。

    /// 
    /// 用户登录
    /// 
    ///子类并不映射到任何数据库,加上一个不映射的属性[NotMapped]
    [NotMapped]
    public class SysComUserLogin
    {

        [Display(Name = "登录名", Description = "4-20个字符")]
        [Required(ErrorMessage = "×")]
        [StringLength(20, MinimumLength = 4, ErrorMessage = "×")]
        public string LoginName { get; set; }

        [Display(Name = "登录密码", Description = "6-20个字符")]
        [Required(ErrorMessage = "×")]
        [StringLength(20, MinimumLength = 6, ErrorMessage = "×")]
        [DataType(DataType.Password)]
        public new string Password { get; set; }

        [Display(Name = "验证码", Description = "请输入验证码!")]
        [Required(ErrorMessage = "×")]
        [StringLength(4, MinimumLength = 4, ErrorMessage = "×")]
        public string VerificationCode { get; set; }
    }

   第二步:控制器Conrallers方法的实现。这里我们考虑有三个:一个是默认的登录页面方法,一个是HTTPPOST提交登录数据的方法,还有一个注销的方法。如下:

        /// 
        /// 用户登录页面
        /// 
        /// 
        public ActionResult UserLogin()
        {
            return View();
        }

        /// 
        /// 用户提交登录
        /// 
        /// 
        /// 
        [HttpPost]
        public ActionResult UserLogin(SysComUserLogin userLogin)
        {
            //说明:因为在Models中,已经实现用户名和密码验证规则,因为这里不需要重复判断了,但验证码除外,因为它是保存Session缓存中.
            if (String.IsNullOrEmpty(Session["VerificationCode"].ToString()))
            {
                ModelState.AddModelError("VerificationCode", "×");
                return View();
            }
            else if (Session["VerificationCode"].ToString() != userLogin.VerificationCode)
            {
                ModelState.AddModelError("VerificationCode", "×");
                return View();
            }
            else
            {
                if (userRpy.Authentication(userLogin.LoginName,userLogin.Password) == 0)
                {
                    HttpCookie _cookie = new HttpCookie("user");
                    _cookie.Values.Add("loginname", userLogin.LoginName);
                    _cookie.Values.Add("password", userLogin.Password);
                    Response.Cookies.Add(_cookie);
                    ModelState.AddModelError("Message", "登陆成功!!");
                    return View();
                }
                else
                {
                    ModelState.AddModelError("Message", "登陆失败!");
                    return View();

                }
            }

        }


        /// 
        /// 注销登录信息
        /// 
        /// URL
        public ActionResult UserLoginOut()
        {
            HttpCookie _cookie = HttpContext.Request.Cookies["user"];
            if (_cookie != null)
            {
                //失效时间
                _cookie.Expires = DateTime.Now.AddHours(-1);
                Response.Cookies.Add(_cookie);
            }
            return View();
        }

  这里面用到一个Authentiction()用户身份验证方法,所以需要在BLL业务层实现。

   第三步:BLL业务逻辑层方法实现

        /// 
        /// 用户登录身份验证
        /// 
        /// 登录名
        /// 密码
        /// 0:登录成功;1:登录名不存在;2:密码错误
        public int Authentication(string loginName, string password)
        {
            var _user = HillstoneContext.SysComUser.SingleOrDefault(u=>u.LoginName==loginName);
            if (_user == null) { return 1; }
            if (_user.Password != password) { return 2; }
            return 0;
        }

   第四步:所有涉及的东西都写完了,下面就是实现VIEW了。如下:

@model Hillstone.Models.SysComUserLogin

@{
    ViewBag.Title = "用户登录";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

UserLogin

@using (Html.BeginForm()) {     @Html.AntiForgeryToken()     @Html.ValidationSummary(true)     
        SysComUserLogin                      @Html.LabelFor(model => model.LoginName)         
                     @Html.EditorFor(model => model.LoginName)             @Html.ValidationMessageFor(model => model.LoginName)             @Html.DisplayDescriptionFor(model=>model.LoginName)         
                     @Html.LabelFor(model => model.Password)         
                     @Html.PasswordFor(model => model.Password)             @Html.DisplayDescriptionFor(model => model.LoginName)                               @Html.LabelFor(model => model.VerificationCode)                               @Html.TextBoxFor(model => model.VerificationCode)             @Html.ValidationMessageFor(model => model.VerificationCode)                             换一张                   

            @Html.ValidationMessage("Message")         

     }
    @Html.ActionLink("Back to List", "Index")
    function VerificationChange() {         $("#verificationcode").attr("src", "/SysComUser/VerificationCode?" + new Date());     }     @section Scripts {     @Scripts.Render("~/bundles/jqueryval") }

   第五部:其他考虑,我们登录后,每次页面跳转或者刷新,需要确认身份是否失效或者有效,那么问题就来了,是不是在所有的页面请求Contraller时候都要调用BLL中的Authencation()方法来验证呢?其实系统默认有验证机制类库,我们可以重新写这个接口,使用起来更加简洁方面,提交我们的开发效率。所以我做个扩展,在Extensions文件夹中新建UserAuthorizeAttribute.cs类。如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Hillstone.BLL;

namespace System.Web.Mvc
{
    /// 
    /// 用户权限验证
    /// 
    public class UserAuthorizeAttribute:AuthorizeAttribute
    {
        /// 
        ///  核心【验证用户是否登录】以后只要在需要登录后才能操作的Action或Controller上加[UserAuthorize]就可实现验证是否已经登录了。
        /// 
        /// HTTP请求
        /// 布尔值:True or False
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.Request.Cookies["user"] == null) return false;
            HttpCookie _cookie = httpContext.Request.Cookies["user"];

            string _loginName = _cookie["loginname"];
            string _password = _cookie["password"];

            httpContext.Response.Write("登录名:" + _loginName);

            if (string.IsNullOrEmpty(_loginName) || string.IsNullOrEmpty(_password)) return false;

            SysComUserRepository userRsy = new SysComUserRepository();
            if (userRsy.Authentication(_loginName, _password) == 0) return true;
            else return false;
        }
    }
}

 继承AuthorizeAttribute类库,这里做AuthorizeCore方法重写,里面调用BLL中的Authencation()登录验证方法。 以后所有需要登录之后才能操作的Contraller中,在Action之前加上[UserAuthorize]即可。

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


当前题目:三、Asp.NetMVC4.0开发CMS系统案例之用户登录模块开发-创新互联
网页网址:http://cdkjz.cn/article/jjgoj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220