MVC5 website Development user Registration (IV) _ Practical skills

Source: Internet
Author: User
Tags generator

Changes to the default Web project
This part of the user or do it yourself, so delete automatically generated user-related code.

Second, add Member area
Right-click on the Web project to add a zone member.

Add Home Controller, select MVC5 Controller-NULL

We add a view to public ActionResult Index (), which is simple to display the user name

 viewbag.title = "Member Center";


Let's run it first and make a mistake.

This is because there are two controllers named home in the project, and you must add namespaces to the route. First open the memberarearegistration in the zone to add namespaces.

Then open the Routeconfig in the project and add namespaces

And then refresh the browser, you can display the normal.

Then add the user controller Usercontroller.

Iii. Changes to model classes
Here first the models project user model is modified, the original consideration is that each user can only belong to a user group, and then carefully considered, or not appropriate, such as a user concurrently more than one role, so still the user and user groups changed to a one-to-many relationship.

    • The user model. Delete the GroupID in the model and delete the foreign key group.
    • Role model. Originally UserGroup (user group) changed to role, considering the sense of authority management is called the role of the group more appropriate, the other role of the meaning of a broader, can refer to the user group, can also refer to the position, can also refer to the department ... The modified code is as follows:
Using System.ComponentModel.DataAnnotations; namespace Ninesky.models {///<summary>///role///<remarks>///created: 2014.02.02///modification: 2014.02.16///&L

 T;/remarks>///</summary> public class Role {[Key] public int Roleid {get; set;} <summary>///name///</summary> [Required (errormessage= "required")] [Stringlength (minimumlength = 2, ERR

 Ormessage = "{1} to {0}")] [Display (name= name)] public string name {get; set;} <summary>///role type <br/>///0 Normal (normal registered user), 1 privileges (such as VIP type), 3 admin (type of admin privilege)///</summary> [Required (Er

 Rormessage = "required")] [Display (Name = user group type)] public int Type {get; set;} <summary>///Description///</summary> [Required (errormessage = "required")] [Stringlength (errormessage = "less than {0]

 } "[Display (Name = description]]] public string Description {get; set;} 
 <summary>///Get role type name///</summary>///<returns></returns> public string typetostring ()
{ Switch (Type) {case 0:return "normal";
 Case 1:return "privilege";
 Case 2:return "Management";
 Default:return "Unknown"; }

Userrolerelation class. In the models project, add the role relationship class Userrolerelation class, code:

Using System.ComponentModel.DataAnnotations;

Namespace Ninesky.models
 ///User Role Relationship
 ///creation: 2014.02.16
 ///</summary> public
 class userrolerelation
 public int Relationid {get; set;}

 ///User ID
 [Required ()] public
 int UserID {get; set;}
 ///role ID
 [Required ()] public
 int Roelid {get; set;}

Nineskydbcontext class. The blue box below is the modified part and the red box is the new increment

Third, authentication code and SHA256 encryption
1. Verification Code
Now the verification code is the website must function, I have the authentication code function divides into three pieces: creates the authentication code character, generates the picture according to the verification code, the User controller action saves the authentication code and returns the picture.

Create a CAPTCHA character createverificationtext ()

Add the security class in the common to generate the Authenticode string in the class using the Pseudo-Random number generator.

 ///Create Authenticode characters
 ///<param name= "Length" > Character length </param>
 ///<returns> Authenticode character </returns> public
 static string createverificationtext (int length)
 char[] _verification = new Char[length];
 Char[] _dictionary = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' S ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '};
 Random _random = new Random ();
 for (int i = 0; i < length; i++) {_verification[i] = _dictionary[_random. Next (_dictionary. LENGTH-1)]; Return
 new String (_verification);

Generate a picture createverificationimage () based on the verification code
The idea is to create the canvas using GDI +, generate the gradient brush with the pseudo-random number generator, and then create the gradient text.

&lt;summary&gt;///Create a captcha picture///&lt;/summary&gt;///&lt;param name= "Verificationtext" &gt; Authenticode code string &lt;/param&gt;// /&lt;param name= "width" &gt; Picture width &lt;/param&gt;///&lt;param name= "height" &gt; Picture length &lt;/param&gt;///&lt;returns&gt; Pictures &lt;/returns&gt; public static Bitmap createverificationimage (string verificationtext, int width, int height) {Pen _
 pen= new Pen (Color.Black);
 Font _font = new Font ("Arial", fontstyle.bold);
 Brush _brush = null;
 Bitmap _bitmap = new Bitmap (width,height);
 Graphics _g = Graphics.fromimage (_bitmap);
 SizeF _totalsizef = _g.measurestring (Verificationtext,_font);
 SizeF _curcharsizef;
 PointF _startpointf = new PointF ((width-_totalsizef.width)/2, (Height-_totalsizef.height)/2);
 Random number generator Random _random =new Random ();
 _g.clear (Color.White); for (int i=0;i&lt;verificationtext.length;i++) {_brush = new LinearGradientBrush (new Point (0,0), new Point (1,1), Color.FromArgb (_random. Next (255), _random. Next (255), _random. Next (255)), Color.FromArgb (_randOm. Next (255), _random. Next (255), _random.
 Next (255)); _g.drawstring (Verificationtext[i].
 ToString (), _font,_brush,_startpointf); _curcharsizef = _g.measurestring (Verificationtext[i].
 ToString (), _font);
 _startpointf.x+= _curcharsizef.width;
 } _g.dispose ();
 return _bitmap; }

The user controller action saves the CAPTCHA and returns a picture
First add the user controller and add the controller Usercontroller to the member zone. Write a Verificationcode method in the controller. The process is: in the method we first create a 6-bit captcha string-> use Createverificationimage to create a captcha picture-> write the picture to the OutputStream-> to write the captcha string to the TempData.

Save in the TempData and session of the difference: TempData only once, that is, passed to the next action, the action code will be destroyed after the execution of the session will continue to save, so the verification code with TempData more appropriate.

 ///Verification Code
 Public ActionResult Verificationcode ()
 string verificationcode = Security.createverificationtext (6);
 Bitmap _img = Security.createverificationimage (Verificationcode, 160,);
 _img. Save (Response.outputstream, System.Drawing.Imaging.ImageFormat.Jpeg);
 tempdata["Verificationcode"] = Verificationcode.toupper ();
 return null;

Let's take a look at the build Diagram verification code effect:

2, Sha256 encryption
Add a static method Sha256 (string plaintext) to the common project's security class

 ///256-bit hash encryption
 ///<param name= "PlainText" > Clear text </param >
 ///<returns> redaction </returns> public
 static string Sha256 (string plaintext)
 SHA256Managed _sha256 = new sha256managed ();
 byte[] _ciphertext = _sha256.computehash (Encoding.Default.GetBytes (plaintext));
 Return convert.tobase64string (_ciphertext);

Iv. Registration
To add a registered view model to Ninesky.Web.Areas.Member.Models

Using System.ComponentModel.DataAnnotations; Namespace Ninesky.Web.Areas.Member.Models {public class Registerviewmodel {///&lt;summary&gt;///username///&lt;/sum mary&gt; [Required (errormessage = "required")] [Stringlength (minimumlength = 4, errormessage = "{2} to {1} characters")] [Display (Na

 me = "user name")] public string UserName {get; set;} &lt;summary&gt;///Display name///&lt;/summary&gt; [Required (errormessage = "required")] [Stringlength (minimumlength = 2,

 ErrorMessage = "{2} to {1} characters")] [Display (name = display name)]] public string DisplayName {get; set;} &lt;summary&gt;///password///&lt;/summary&gt; [Required (errormessage = "required")] [Display (Name = "password")] [Stringlength (

 20,minimumlength=6,errormessage= "{2} to {1} characters")] [DataType (Datatype.password)] public string Password {get; set;} &lt;summary&gt;///Confirm Password///&lt;/summary&gt; [Required (errormessage = "required")] [Compare ("Password", errormessage = "Two input passwords inconsistent")] [Display (Name = "Confirm password")] [DataType (Datatype.password)] PUblic string ConfirmPassword {get; set;} &lt;summary&gt;///mailbox///&lt;/summary&gt; [Required (errormessage = "required")] [Display (Name = "Mailbox")] [DataType (Data

 type.emailaddress,errormessage= "Incorrect email format")] public string Email {get; set;} &lt;summary&gt;///Verification Code///&lt;/summary&gt; [Required (errormessage = "required")] [Stringlength (6, minimumlength = 6, E
 Rrormessage = "Incorrect Authenticode"] [Display (Name = "Authenticode")]] public string Verificationcode {get; set;}

Add a register () action in Usercontroller and return directly to the strongly typed (Registerviewmodel) view

 Public ActionResult Register ()
 View ();


@model Ninesky.Web.Areas.Member.Models.RegisterViewModel @{viewbag.title = "registered";
Layout = "~/views/shared/_layout.cshtml"; @using (Html.BeginForm ()) {@Html. AntiForgeryToken () &lt;div class= "Form-horizontal" &gt; &lt;h4&gt; user Registration &LT;/H4&G
 T &lt;hr/&gt; @Html. ValidationSummary (True) &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. UserName, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (model =&gt; model. UserName) @Html. Validationmessagefor (model =&gt; model. UserName) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. DisplayName, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (model =&gt; model. DisplayName) @Html. Validationmessagefor (model =&gt; model. DisplayName) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Password, new {@class = "Control-label col-md-2"}) &lt;div Class= "col-md-10" &gt; @Html. Editorfor (model =&gt; model. Password) @Html. Validationmessagefor (model =&gt; model. Password) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. ConfirmPassword, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (model =&gt; mo Del. ConfirmPassword) @Html. Validationmessagefor (model =&gt; model. ConfirmPassword) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Email, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (model =&gt; model. Email) @Html. Validationmessagefor (model =&gt; model. Email) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Verificationcode, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (Model =&gt; m Odel. Verificationcode) &lt;img id= "Verificationcode" title= "click Refresh" src= "@Url. Action (" verificAtioncode ")" style= "Cursor:pointer"/&gt; @Html. Validationmessagefor (model =&gt; model. Verificationcode) &lt;/div&gt; &lt;/div&gt; &lt;div class= "checkbox" &gt; &lt;input type= "checkbox" checked= "Checked" R equired/&gt; I agree with &lt;a href= "#" &gt; User Registration Agreement &lt;/a&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; &lt;div class= "col-m D-offset-2 col-md-10 "&gt; &lt;input type=" Submit "value=" registered "class=" btn btn-default "/&gt; &lt;/div&gt; &lt;/div&gt; & lt;/div&gt;} &lt;script type= "Text/javascript" &gt; $ ("#verificationcode"). Click (function () {$ ("#verificationcode")
 . attr ("src", "@Url. Action (" Verificationcode ")" + New Date ()); }) &lt;/script&gt; @section Scripts {@Scripts. Render ("~/bundles/jqueryval")}

Then add the public actionresult Register (Registerviewmodel register) to the user controller to process user-submitted registration data

 [HttpPost] [Validateantiforgerytoken] public ActionResult Register ( Registerviewmodel register) {if (tempdata["verificationcode"] = = NULL | | tempdata["Verificationcode"]. ToString ()!= register.
 Verificationcode.toupper ()) {Modelstate.addmodelerror ("Verificationcode", "Incorrect verification Code");
 return View (register); } if (Modelstate.isvalid) {if (userservice.exist) (register.
 UserName)) Modelstate.addmodelerror ("UserName", "User name already exists"); else {User _user = new User () {UserName = register. UserName,///Default user group code written here DisplayName = register. DisplayName, Password = security.sha256 (register. Password),//e-mail verification and Mailbox Uniqueness issue email = register.
  Email,//user status Problem status = 0, registrationtime = System.DateTime.Now};
  _user = Userservice.add (_user); if (_user. UserID > 0 {return Content ("Registered success!")
  Authenticationmanager.signin (); else {modelstate.addmodelerror ("", "Registration failed!)
 "); }
 return View (register); }

Many of the root user settings related to the code will not be considered in the first place, and so on when the user is set. When registration fails, return to the view and display an error, successful return to the view registration success, and so the next time to do the user login can be registered directly to the user login. Look at the effect.

Click Register to register successfully.

A simple user registration is complete, mainly has the authentication code, SHA256 encryption, registers the view model, verifies the user submits the data and saves and so on the step. The latter is the user registration, the registration will use Claimsidentity and Httpcontext.getowincontext (). Authentication.signin ();

This article has been organized into the " MVC Web Development Course", welcome you to learn to read, more content can also refer to MVC5 website Development topic study.

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.

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: 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.