3. Asp.Net MVC4.0 CMS 시스템 개발 사례의 사용자 로그인 모듈 개발
                                            
 8638 단어  mvcModel사용자 로그인Contrallers
                    
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; }
    }2단계: 컨트롤러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 업무층에서 실현해야 한다.
3단계: 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;
        }4단계: 관련된 모든 것을 다 썼습니다. 다음은 VIEW를 실현하는 것입니다.다음과 같습니다.
@model Hillstone.Models.SysComUserLogin
@{
    ViewBag.Title = "    ";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>UserLogin</h2>
@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" style="cursor: pointer">   </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")
}5부: 다른 고려사항은 우리가 로그인한 후에 매번 페이지가 바뀌거나 갱신될 때마다 신원이 효력을 상실하거나 유효한지 확인해야 한다는 것이다. 그러면 문제가 생겼다. 모든 페이지에서 Contraller를 요청할 때 BLL의Authencation() 방법을 사용해서 검증해야 하는가?사실 시스템은 기본적으로 검증 메커니즘 라이브러리가 있기 때문에 우리는 이 인터페이스를 다시 쓸 수 있고 사용하기에 더욱 간결한 측면에서 우리의 개발 효율을 제출할 수 있다.그래서 Extensions 폴더에 User Authorize Attribute를 새로 만듭니다.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;
        }
    }
}Authorize Attribute 라이브러리를 계승합니다. Authorize Core 방법으로 다시 쓰고, BLL의 Authencation () 로그인 검증 방법을 호출합니다.나중에 로그인해야 작동하는 모든 Contraller에는 Action 전에 [UserAuthorize]를 추가하면 됩니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
클린 아키텍처의 Presenter를 이해하기 어려운 것은 MVC 2가 아니기 때문에클린 아키텍처에는 구체적인 클래스 구성 예를 보여주는 다음 그림이 있습니다. 이 그림 중에서 Presenter와 Output Boundary(Presenter의 인터페이스)만 구체 구현을 이미지하는 것이 매우 어렵다...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.