三、Asp.Net MVC4.0 CMSシステム事例を開発するユーザー登録モジュール開発


今回の開発では、3階層アーキテクチャとMVCを組み合わせて、次のシステム構造を見てみましょう.
    View ->Contraller->Model->BLL->DAL->SQLSERVER
             |        |        |
             ----------->Extensions----->FrameWork
             |
             __>Common
Extensionsには、コントロールの再確認、権限の再検証など、拡張クラス機能が含まれています.Commonはいくつかの共通機能です.
ステップ1:ユーザー・ログイン・モデルを作成し、登録モデル・クラス(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がログインデータをコミットするメソッドと、ログアウトするメソッドの3つを考慮します.次のようになります.
        /// <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();
        }

ここではAuthentication()ユーザ認証方法が用いられるため、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;
        }

第四歩:すべての関連するものはすべて書き終わって、次は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")
}

第五部:その他の考慮では、私たちがログインした後、ページがジャンプしたりリフレッシュしたりするたびに、身分が失効したり有効であるかどうかを確認する必要があります.では、問題は来ました.すべてのページが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]を付けるとよい.