三、Asp.Net MVC4.0开发CMS系统案例之用户登录模块开发

发布时间:2020-09-30 22:22:16 作者:sujerhy
来源:网络 阅读:3264

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

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

             |        |        |

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

             |

             __>Common


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


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

    /// <summary>
    /// 用户登录
    /// </summary>
    ///子类并不映射到任何数据库,加上一个不映射的属性[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提交登录数据的方法,还有一个注销的方法。如下:

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

        /// <summary>
        /// 用户提交登录
        /// </summary>
        /// <param name="userLogin"></param>
        /// <returns></returns>
        [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();

                }
            }

        }


        /// <summary>
        /// 注销登录信息
        /// </summary>
        /// <returns>URL</returns>
        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业务逻辑层方法实现

        /// <summary>
        /// 用户登录身份验证
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="password">密码</param>
        /// <returns>0:登录成功;1:登录名不存在;2:密码错误</returns>
        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";
}

<h3>UserLogin</h3>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>SysComUserLogin</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.LoginName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LoginName)
            @Html.ValidationMessageFor(model => model.LoginName)
            @Html.DisplayDescriptionFor(model=>model.LoginName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.DisplayDescriptionFor(model => model.LoginName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.VerificationCode)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.VerificationCode)
            @Html.ValidationMessageFor(model => model.VerificationCode)
             <img id="verificationcode" alt="" src="@Url.Action("VerificationCode", "SysComUser")" /> 
             <a id="trydifferent" >换一张</a> 
        </div>

        <p>
            <input type="submit" value="Save" />@Html.ValidationMessage("Message")
        </p>
    </fieldset>
}

<div>

    @Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript" >
    function VerificationChange() {
        $("#verificationcode").attr("src", "/SysComUser/VerificationCode?" + new Date());
    }
   
</script>
@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
{
    /// <summary>
    /// 用户权限验证
    /// </summary>
    public class UserAuthorizeAttribute:AuthorizeAttribute
    {
        /// <summary>
        ///  核心【验证用户是否登录】以后只要在需要登录后才能操作的Action或Controller上加[UserAuthorize]就可实现验证是否已经登录了。
        /// </summary>
        /// <param name="httpContext">HTTP请求</param>
        /// <returns>布尔值:True or False</returns>
        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]即可。


推荐阅读:
  1. Asp.NET WebApi+Redis实现单用户登录实战演练
  2. Asp.Net MVC4.0如何开发栏目内容模型管理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mvc 用户登录 model

上一篇:如何用vue-cli3脚手架搭建一个基于ts的基础脚手架的方法

下一篇:oracle常见的几种数据类型 Oracle 10g学习系列(3)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》