ASP. NET MVC4.0 Development CMS system case User Login module development

Source: Internet
Author: User

This development is a combination of three-tier architecture and MVC, we look at the following system structure:

View->contraller->model->bll->dal->sqlserver

|        | |

----------->extensions----->framework

|

__>common


Extensions includes extension class features such as re-authentication of controls, re-validation of permissions, and so on. Common are some of the public features.


The first step: Create a user login model that can be written to the same file as the Registered model class (Syscomuerregister), the user model (Syscomuser).

    /// <summary>    ///  User Login     / The  </summary>    ///sub-class does not map to any database, plus an unmapped property [notmapped]    [ notmapped]    public class syscomuserlogin    {         [display (name =  "Login name", description =  "4-20 characters")]         [required (errormessage =  "x")]         [stringlength (20, minimumlength = 4, errormessage =   "x")]        public string loginname { get;  set; }        [display (name =  "Login password",  description =  "6-20 characters")]        [required (ErrorMessage  =  "x")]&NBSP;&NBSP;&NBsp;     [stringlength (20, minimumlength = 6, errormessage =   "x")]        [datatype (Datatype.password)]         public new string password { get; set; }         [display (name =  "Verification Code", description =  "Please enter the verification code!")         [required (errormessage =  "x")]         [stringlength (4, minimumlength = 4, errormessage =   "x")]        public string verificationcode {  get; set; }    }

     Step Two: implementation of the Controller Conrallers method. Here we consider three: one is the default login page method, one is httppost to submit the login data method, there is a method of logoff. As follows:

        /// <summary>         ///  User Login Page         /// </summary>         /// <returns></returns>         public actionresult userlogin ()          {            return view ();         }        /// <summary>         ///  User Submit Login          /// </summary>        /// <param name= " Userlogin "></param>        /// <returns></ returns>        [httppost]        public actionresult  userlogin (Syscomuserlogin userlogin)         {             //Description: Because the user name and password validation rules have been implemented in models, there is no need to repeat the judgment, except for the verification code Because it is saved in the session cache in .            if  ( String.IsNullOrEmpty (session["Verificationcode"). ToString ()))             {                 modelstate.addmodelerror (" Verificationcode ", " x ");                 return view ();             }             else if  (session["VeriFicationcode "]. ToString ()  != userlogin.verificationcode)              {                 modelstate.addmodelerror ("Verificationcode",  "x");                 return view ();             }            else             {                 if  (Userrpy.authentication ( Userlogin.loginname,userlogin.password)  == 0)                  {                &nbSp;    httpcookie _cookie = new httpcookie ("user");                     _cookie. Values.add ("LoginName",  userlogin.loginname);                     _cookie. Values.add ("password",  userlogin.password);                     response.cookies.add (_cookie);                      Modelstate.addmodelerror ("Message",  "Landing success!! ");                     return view ();                 }                 else                 {                      Modelstate.addmodelerror ("Message",  "Login failed!") ");                     return view ();                 }            }         }        /// <summary>         ///  Sign Out of login information          /// </summary>        /// <returns>url</returns>        public actionresult  Userloginout ()         {             httpcookie _cookie = httpcontext.request.cookies["User"];             if  (_cookie != null)              {                 //Expiry Time                  _cookie. Expires = datetime.now.addhours ( -1);                 response.cookies.add (_cookie);             }         &nbsP;  return view ();         } 

A authentiction () user authentication method is used here, so it needs to be implemented in the BLL business layer.


The third step: the implementation of the BLL business Logic Layer method

        /// <summary>         ///  User logon authentication         /// </summary>         /// <param name= "LoginName" > Sign-in Name </param>         /// <param name= "password" > Password </param>         /// <returns>0: Login successful; 1: Login name does not exist; 2: Password error </returns>         public int authentication (string loginName,  String password)         {             var _user = hillstonecontext.syscomuser.singleordefault (u= >u.loginname==loginname);            if  (_ User == null) &nbsP { return 1; }            if  (_ User. Password != password)  { return 2; }             return 0;        }

     Fourth: All the things involved are finished, here is the implementation view. as follows:

@model  Hillstone.Models.SysComUserLogin@{    ViewBag.Title =  "User Login";     Layout =  "~/views/shared/_layout.cshtml";} 

     Fifth: Other considerations, after we log in, each page jump or refresh, you need to confirm that the identity is invalid or valid, then the problem is coming, Do you want to call the Authencation () method in the BLL to verify that all pages are requesting Contraller? In fact, the system default has a validation mechanism class library, we can re-write this interface, use more concise aspects, to submit our development efficiency. So I'll make an extension and create a new UserAuthorizeAttribute.cs class in the Extensions folder. As follows:

Using system;using system.collections.generic;using system.linq;using system.web;using  Hillstone.BLL;namespace System.Web.Mvc{    /// <summary>     ///  User Rights Verification     /// </summary>    public  class UserAuthorizeAttribute:AuthorizeAttribute    {         /// <summary>        ///    Core "Verify that the user is logged in" will be able to verify that you are logged in by adding [Userauthorize] on an action or controller that requires login to be able to do so.         /// </summary>         /// <param name= "HttpContext" >http request </param>         /// <returns> Boolean value:true or false</returns>         protected override bool&nBsp 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 ("Login name:"  + _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;         }    }}

Inherit the Authorizeattribute class library, where you do the Authorizecore method rewrite, which calls the Authencation () login verification method in the BLL. After all the contraller that need to be logged in, add [Userauthorize] before the action.


This article is from the "Run small snail-original space" blog, please be sure to keep this source http://songjiahao.blog.51cto.com/4433831/1581813

ASP. NET MVC4.0 Development CMS system case User Login module development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.