Home>

The basic framework was set up last time,This time I started the whole web part, and finally I can see the interface a little excited.The web project part starts with user functions,Basically registered,Login, logout, search, view, delete, etc. involve the member area and the manage area.

Changes to the default web project

The user part is still done by themselves,So delete the automatically generated user-related code.

Second, add the member area

Right-click on the web project and add the area member.

Add home controller, select mvc5 controller-empty

We add a view to public actionresult index (),The code is very simple.

@ {
 viewbag.title="Member Center";
}
<h2>[email protected]
 </h2>

Let's run it first,Something went wrong.

This is because there are two controllers named home in the project,You must include a namespace in the route.First open the memberarearegistration in the area to add a namespace.

Then open the routeconfig in the project and add the namespace

Refresh your browser again,Can be displayed normally.

Add the user controller usercontroller.

Third, the model class changes

First modify the models project user model here,The original consideration was that each user can belong to only one user group.After careful consideration,Still not suitable,For example, a user has multiple roles,So still change the user and user group into a one-to-many relationship.

user model. Delete the groupid in the model and delete the foreign key group. role model. The original usergroup (user group) was changed to a role,Considering that rights management feels that calling roles is more appropriate than calling household groups,In addition, the role has a wider meaning,Can be a user group,Can also refer to positions,Can also refer to the department ... The modified code is as follows:
using system.componentmodel.dataannotations;
namespace ninesky.models
{
 ///<summary>
 ///Roles
 ///<remarks>
 ///Created:2014.02.02
 ///Modification:2014.02.16
 ///</remarks>
 ///</summary>
 public class role
 {
 [key]
 public int roleid {get;set;}
 ///<summary>
 ///name
 ///</summary>
 [required (errormessage="required")]
 [stringlength (20, minimumlength=2, errormessage="{1} to {0} words")]
 [display (name="name")]
 public string name {get;set;}
 ///<summary>
 ///character type<br />
 ///0 ordinary (ordinary registered user), 1 privilege (type like VIP), 3 management (type of management authority)
 ///</summary>
 [required (errormessage="Required")]
 [display (name="User Group Type")]
 public int type {get;set;}
 ///<summary>
 ///description
 ///</summary>
 [required (errormessage="Required")]
 [stringlength (50, errormessage="less than {0} words")]
 [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 "privileged";
 case 2:
  return "management";
 default:
  return "unknown";
 }
 }
 }
}

userrolerelation class. Add roleroles to userrolerelation in the models project. Code:

using system.componentmodel.dataannotations;
namespace ninesky.models
{
 ///<summary>
 ///user role relationship
 ///<remarks>
 ///Created:2014.02.16
 ///</remarks>
 ///</summary>
 public class userrolerelation
 {
 [key]
 public int relationid {get;set;}
 ///<summary>
 ///user id
 ///</summary>
 [required ()]
 public int userid {get;set;}
 ///<summary>
 ///role id
 ///</summary>
 [required ()]
 public int roelid {get;set;}
 }
}

nineskydbcontext class. The blue box is the modified part as shown below.Red box is newly added

Third, the verification code and sha256 encryption

1.Verification codeVerification codes are now a required feature of websites,I divided the verification code function into three parts:create verification code characters, generate pictures based on the verification code, save the verification code in the user controller action, and return the picture.

Create verification code character createverificationtext ()

Add the security class to common, and use a pseudo-random number generator to generate a verification code string in the class.

///<summary>
 ///create verification code character
 ///</summary>
 ///<param name="length">character length</param>
 ///<returns>verification code 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 image based on verification code createverificationimage ()

The idea is to use gdi + to create the canvas,Generate a gradient brush using a pseudo-random number generator,Then create gradient text.

///<summary>
 ///Create a verification code image
 ///</summary>
 ///<param name="verificationtext">verification code string</param>
 ///<param name="width">image width</param>
 ///<param name="height">image length</param>
 ///<returns>picture</returns>
 public static bitmap createverificationimage (string verificationtext, int width, int height)
 {
 pen _pen=new pen (color.black);
 font _font=new font ("arial", 14, 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<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;
 }

Save the verification code in the user controller action and return the picture

First add the user controller and add the controller usercontroller in the member area. Write a verificationcode method in the controller. The process is:in the method we first create a 6-digit verification code string->create a verification code picture using createverificationimage->write the picture to outputstream->write the verification code string into tempdata

The difference between stored in tempdata and session:tempdata is only passed once,That is, after passing to the next action, the action code will be destroyed after execution.session will be saved continuously,So tempdata is more suitable for verification code.

///<summary>
 ///verification code
 ///</summary>
 ///<returns></returns>
 public actionresult verificationcode ()
 {
 string verificationcode=security.createverificationtext (6);
 bitmap _img=security.createverificationimage (verificationcode, 160, 30);
 _img.save (response.outputstream, system.drawing.imaging.imageformat.jpeg);
 tempdata ["verificationcode"]=verificationcode.toupper ();
 return null;
 }

Let's see the effect of generating a verification code:

2.sha256 encryption

Add the static method sha256 (string plaintext) to the security class of the common project

///<summary>
 ///256-bit hash encryption
 ///</summary>
 ///<param name="plaintext">plaintext</param>
 ///<returns>ciphertext</returns>
 public static string sha256 (string plaintext)
 {
 sha256managed _sha256=new sha256managed ();
 byte [] _ciphertext=_sha256.computehash (encoding.default.getbytes (plaintext));
 return convert.tobase64string (_ciphertext);
 }

Fourth, registration

Add registered view models in ninesky.web.areas.member.models

using system.componentmodel.dataannotations;
namespace ninesky.web.areas.member.models
{
 public class registerviewmodel
 {
 ///<summary>
 ///username
 ///</summary>
 [required (errormessage="Required")]
 [stringlength (20, minimumlength=4, errormessage="{2} to {1} characters")]
 [display (name="User Name")]
 public string username {get;set;}
 ///<summary>
 ///display name
 ///</summary>
 [required (errormessage="Required")]
 [stringlength (20, minimumlength=2, errormessage="{2} to {1} characters")]
 [display (name="Display Name")]
 public string displayname {get;set;}
 ///<summary>
 ///password
 ///</summary>
 [required (errormessage="Required")]
 [display (name="Password")]
 [stringlength (20, minimumlength=6, errormessage="{2} to {1} characters")]
 [datatype (datatype.password)]
 public string password {get;set;}
 ///<summary>
 ///confirm password
 ///</summary>
 [required (errormessage="Required")]
 [compare ("password", errormessage="The passwords entered twice do not match")]
 [display (name="Confirm Password")]
 [datatype (datatype.password)]
 public string confirmpassword {get;set;}
 ///<summary>
 ///email
 ///</summary>
 [required (errormessage="Required")]
 [display (name="Mailbox")]
 [datatype (datatype.emailaddress, errormessage="email is malformed")]
 public string email {get;set;}
 ///<summary>
 ///verification code
 ///</summary>
 [required (errormessage="Required")]
 [stringlength (6, minimumlength=6, errormessage="The verification code is incorrect")]
 [display (name="Verification Code")]
 public string verificationcode {get;set;}
 }
}

Add register () action in usercontroller and return directly to strongly typed (registerviewmodel) view

///<summary>
 ///Register
 ///</summary>
 ///<returns></returns>
 public actionresult register ()
 {
 return view ();
 }

view

@model ninesky.web.areas.member.models.registerviewmodel
@ {
 viewbag.title="Register";
 layout="~/views/shared/_layout.cshtml";
}
@using (html.beginform ())
{
 @ html.antiforgerytoken ()
 <div>
 <h4>User Registration</h4>
 <hr />
 @ html.validationsummary (true)
 <div>
 @ html.labelfor (model =>model.username, new {@class="control-label col-md-2"})
 <div>
 @ html.editorfor (model =>model.username)
 @ html.validationmessagefor (model =>model.username)
 </div>
 </div>
 <div>
 @ html.labelfor (model =>model.displayname, new {@class="control-label col-md-2"})
 <div>
 @ html.editorfor (model =>model.displayname)
 @ html.validationmessagefor (model =>model.displayname)
 </div>
 </div>
 <div>
 @ html.labelfor (model =>model.password, new {@class="control-label col-md-2"})
 <div>
 @ html.editorfor (model =>model.password)
 @ html.validationmessagefor (model =>model.password)
 </div>
 </div>
 <div>
 @ html.labelfor (model =>model.confirmpassword, new {@class="control-label col-md-2"})
 <div>
 @ html.editorfor (model =>model.confirmpassword)
 @ html.validationmessagefor (model =>model.confirmpassword)
 </div>
 </div>
 <div>
 @ html.labelfor (model =>model.email, new {@class="control-label col-md-2"})
 <div>
 @ html.editorfor (model =>model.email)
 @ html.validationmessagefor (model =>model.email)
 </div>
 </div>
 <div>
 @ html.labelfor (model =>model.verificationcode, new {@class="control-label col-md-2"})
 <div>
 @ html.editorfor (model =>model.verificationcode)
 <img src="@ url.action (" verificationcode ")" />
 @ html.validationmessagefor (model =>model.verificationcode)
 </div>
 </div>
 <div>
 <input type="checkbox" checked="checked" required />I agree<a href="#">"User Registration Agreement"</a>
 </div>
 <div>
 <div>
 <input type="submit" value="register" />
 </div>
 </div>
 </div>
}
<script type="text/javascript">
 $("#verificationcode"). click (function () {
 $("#verificationcode"). attr ("src", "@ url.action (" verificationcode ")?" + new date ());
 })
</script>
@section scripts {
 @ scripts.render ("~/bundles/jqueryval")
}

Then add a public actionresult register (registerviewmodel register) in the user controller to handle the registration data submitted by the user

[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", "username already exists");
 else
 {
  user _user=new user ()
  {
  username=register.username,  //The default user group code is written here
  displayname=register.displayname,  password=security.sha256 (register.password),  //Mailbox verification and mailbox uniqueness
  email=register.email,  //User status issues
  status=0,  registrationtime=system.datetime.now
  };
  _user=userservice.add (_user);
  if (_user.userid>0)
  {
  return content ("Registration succeeded!");
  //authenticationmanager.signin ();
  }
  else {modelstate.addmodelerror ("", "Registration failed!");}
 }
 }
 return view (register);
 }

Many root user settings in the code are not considered first,After the user settings are made, they will be modified later.Return to view and display errors when registration fails;When successful, return to the view registration is successful,When the user logs in next time, the user can log in directly after registration.See the effect.

Click Register,registration success.

A simple user registration is complete,There are mainly verification code, sha256 encryption, registering the view model, verifying user submission data and saving.After that is user registration,Registration will use claimsidentity and httpcontext.getowincontext (). Authentication.signin ();

  • Previous jquery image carousel special effects code sharing
  • Next Batch processing to import the file names in File Mania into the corresponding names in the table