MVC4 Making Web Tutorials Chapter II Practical skills of user login 2.2_

Source: Internet
Author: User
Tags httpcontext

A user
1.1 User Registration
1.2 User Login

First, add the user login model class Userlogin in models, which uses only three fields of user name, password and authentication code.

<summary>
 ///User Login model
 ///</summary> public
 class Userlogin
 {
 ///<summary>
 ///username
 ///</summary>
 [Display (name = "Username", Description = "4-20 characters.") ")]
 [Required (errormessage =" x ")]
 [Stringlength (minimumlength = 4, errormessage =" x ")] public
 String UserName {get; set;}
 <summary>
 ///password
 ///</summary>
 [Display (Name = "password", Description = "6-20 characters.") ")]
 [Required (errormessage =" x ")]
 [Stringlength (minimumlength = 6, errormessage =" x ")]
 [DataType ( Datatype.password)] public
 string Password {get; set;}
 <summary>
 ///Verification Code
 ///</summary>
 [Display (Name = "Captcha", Description = "Enter the verification code in the picture.") ")]
 [Required (errormessage =" x ")]
 [Stringlength (6, minimumlength = 6, errormessage =" x ")]
 public String Verificationcode {get; set;}

 }

Add the login action to the Usercontroller, and the code looks as follows:

Public ActionResult Login ()
 {return
  View ();
 }
 [HttpPost]
 Public ActionResult Login (userlogin login)
 {return
  View ();
 }

Use cookies to save login account, password and other information, modify public actionresult login (userlogin login). Modify the completion code as follows:

[HttpPost] public actionresult login (userlogin login) {//Verify authentication code if (session["verificationcode"] = = NULL | | session["Verificationcode"]. ToString () = = "") {Error _e = new Error {Title = "Authentication code does not exist", Details = "When the user registers, the server side of the authentication code is empty, or the authentication code submitted to the server is empty", cause = " ;li> the time you sign up for the registration page has timed out </li><li> you have bypassed the client validation to submit data to the server </li> ", Solution =" return <a href= ' "+
  Url.action ("register", "User") + "' > Registration </a> page, reload after registration"};
  Return redirecttoaction ("Error", "Prompt", _e); else if (session["Verificationcode"). ToString ()!= login.
  Verificationcode.toupper ()) {Modelstate.addmodelerror ("Verificationcode", "X");
  return View ();
  //Verify account password Userrsy = new Userrepository (); If Userrsy.authentication (login. UserName, Common.Text.Sha256 (login.
  Password) = = 0) {HttpCookie _cookie = new HttpCookie ("User"); _cookie. Values.add ("UserName", login.)
  UserName); _cookie. Values.add ("Password", Common.Text.Sha256) (login.
  Password));
  RESPONSE.COOKIES.ADD (_cookie); RetuRN redirecttoaction ("Default", "User"); else {modelstate.addmodelerror ("message", "Login failed!")
  ");
  return View ();

 }

 }

Right-click on public ActionResult Login () to add the enhanced type view

Login.cshtml to complete the offspring

@model CMS.
 Models.userlogin @{viewbag.title = "User Login";
Layout = "~/views/shared/_layout.cshtml"; } <div class= "banner" >  </div> @using (html.begin Form ()) {@Html. ValidationSummary (True) <div class= "form" > <dl> <dt> User Login </dt> <dd& 
  Gt <div class= "label" > @Html. Labelfor (model => model. UserName):</div> <div class= "Ctrl" > @Html. Editorfor (model => model. UserName) @Html. Validationmessagefor (model => model. UserName) @Html. Displaydescriptionfor (model => model. UserName) </div> </dd> <dd> <div class= "label" > @Html. Labelfor (model => model. Password):</div> <div class= "Ctrl" > @Html. Passwordfor (model => model. Password) @Html. Validationmessagefor (model => model. Password) @Html. Displaydescriptionfor (model => model. Password) </div> </dd> <dd> <divclass= "Label" > Authenticode:</div> <div class= "Ctrl" > @Html. Textboxfor (model => model. Verificationcode) @Html. Validationmessagefor (model => model. Verificationcode)  <a I D= "Trydifferent" style= "Cursor:pointer" > Change a </a> </div> </dd> <dd> <div class= "L Abel "></div> <div class=" Ctrl "> <input type=" Submit "value=" Landing "/> @Html. Validationmessage (" Mes 
  Sage "); </div> </dd> </dl> <div class= "clear" ></div> </div>} <script type= "text/ JavaScript "> $ (" #trydifferent "). Click (function () {$ (" #verificationcode "). attr (" src ","/user/verificationcode? ") 
 + new Date ());

 }) </script> @section Scripts {@Scripts. Render ("~/bundles/jqueryval")}

Browser to view the landing page

Click on the landing test. OK login Successful

Verify that the user has logged in, this block, together with permission validation, inherits a custom validation class from the Authorizeattribute

Add a Extensions folder to the project, add a class userauthorizeattribute inherit from Authorizeattribute, rewrite the Authorizecore method to implement the validation that the user has logged in, Permission validation is added when Write permission function

 using Ninesky.repository; namespace SYSTEM.WEB.MVC {///<summary>///user Rights authentication///</summary> public class Userauthorizeattribute:au Thorizeattribute {///<summary>///core "Verifying user Login"///</summary>///<param name= "HttpContext" >< /param>///<returns></returns> protected override bool Authorizecore (HttpContextBase HttpContext) {/
  /check if cookies["user" exists if (httpcontext.request.cookies["user"] = = null) return false;
  Verify that the username password is correct httpcookie _cookie = httpcontext.request.cookies["User";
  String _username = _cookie["UserName"];
  String _password = _cookie["password"];
  HttpContext.Response.Write ("User name:" +_username); if (_username = = "" | |
  _password = = "") return false;
  Userrepository _userrsy = new Userrepository ();
  if (_userrsy.authentication (_username, _password) = = 0) return true;
 else return false; }
 }
}

In the future, you can verify that you have logged in by adding [Userauthorize] on the action or controller that you need to log on.
Exit function, add logout Action in Usercontroller

<summary>
 ///exit system
 ///</summary>
 ///<returns></returns>
 Public ActionResult Logout ()
 {
  if (request.cookies["User"!= null)
  {
  HttpCookie _cookie = request.cookies[" User "];
  _cookie. Expires = DateTime.Now.AddHours ( -1);
  RESPONSE.COOKIES.ADD (_cookie);
  }
  Notice _n = new Notice {Title = "successful Exit", Details = "You have successfully quit!" ", Dwelltime = 5, navigationname=" Homepage ", Navigationurl = Url.action (" Index "," Home ")};
  Return redirecttoaction ("Notice", "Prompt", _n);
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.