Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the user Registration of ASP.NET MVC5 website Development

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to achieve ASP.NET MVC5 website development user registration". In the daily operation, I believe that many people have doubts about how to achieve ASP.NET MVC5 website development user registration. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to achieve ASP.NET MVC5 website development user registration". Next, please follow the editor to study!

I. changes to the default Web project

Users still do this part on their own, so delete the automatically generated user-related code.

2. Add Member area

Right-click on the web project to add a region Member.

Add Home controller, select MVC5 controller-null

Let's add a view to public ActionResult Index (). The code is simple enough to show the user name.

@ {ViewBag.Title = "member Center";} Welcome! @ User.Identity.Name

Let's run it first. We made a mistake.

This is because there are two controllers named Home in the project, and namespaces must be added to the route. First open the MemberAreaRegistration in the area to add a namespace.

Then open the RouteConfig in the project and add a namespace

Then refresh the browser, can display normally.

Then add the user controller UserController.

Third, changes to the model class

Here, we first modify the User model of the Models project. The original consideration is that each user can only belong to one user group, but after careful consideration, it is still not appropriate. For example, a user holds multiple roles, so it is still an one-to-many relationship between the user and the user group.

User model. Delete GroupID from the model and delete the foreign key Group.

Role model. It turns out that UserGroup (user group) has been changed to role, taking into account that rights management feels that role is more appropriate than calling group, and the meaning of role is broader, which can refer to user group, position or department. The modified code is as follows:

Using System.ComponentModel.DataAnnotations;namespace Ninesky.Models {/ role / create: 2014.02.02 / modify: 2014.02.16 / public class Role {[Key] public int RoleID {get; set } / name / / [Required (ErrorMessage= "required")] [StringLength (20, MinimumLength = 2, ErrorMessage= "{1} to {0} words")] [Display (Name= "name")] public string Name {get; set } / role type / 0 normal (normal registered user), 1 privilege (type such as VIP), 3 Administration (type of administrative authority) / [Required (ErrorMessage = "required")] [Display (Name = "user group type")] public int Type {get; set } / description / / [Required (ErrorMessage = "required")] [StringLength (50, ErrorMessage = "less than {0} words")] [Display (Name = "description")] public string Description {get; set;} / public string TypeToString () {switch (Type) {case 0: return "normal"; case 1: return "privilege" Case 2: return "Management"; default: return "unknown";}}

The UserRoleRelation class. Add the role relationship class UserRoleRelation class to the Models project, code:

Using System.ComponentModel.DataAnnotations;namespace Ninesky.Models {/ user role relationship / create: 2014.02.16 / public class UserRoleRelation {[Key] public int RelationID {get; set;} / user ID / [Required ()] public int UserID {get; set;} / role ID / [Required ()] public int RoelID {get; set }}}

The NineskyDbContext class. In the following figure, the blue box is the modified part, and the red box is the new addition.

CAPTCHA and Sha256 encryption

1. Verification code

Now CAPTCHA is a necessary function of the website. I divide the CAPTCHA function into three parts: create CAPTCHA characters, generate pictures according to CAPTCHA, save CAPTCHA in User controller action and return pictures.

Create the CAPTCHA character CreateVerificationText ()

Add the Security class to Common and use the pseudorandom number generator to generate the CAPTCHA string in the class.

/ create CAPTCHA character / character length / CAPTCHA character public static string CreateVerificationText (int length) {char [] _ verification = new char [length] Char [] _ dictionary = {'Aids,' bundles, 'canals,' dudes, 'ethers,' fouls, 'gags,' hacks, 'Iles,' Jacks, 'Kids,' lags, 'masks,' noses, 'oaths,' packs, 'Qoys,' ringing, 'slots,' tweets, 'Utters,' Vaults, 'Wells,' X' Yee, Zhe, a fan, a boy, a girl, a woman, a girl, a girl, a woman, a girl, a woman, a doctor, a 'yawning,' zoning,'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); } 根据验证码生成图片CreateVerificationImage() 思路是使用GDI+创建画布,使用伪随机数生成器生成渐变画刷,然后创建渐变文字。 /// /// 创建验证码图片 /// /// 验证码字符串 /// 图片宽度 /// 图片长度 /// 图片 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 _random =new Random(); _g.Clear(Color.White); for(int i=0;i使用CreateVerificationImage创建验证码图片->

Write the picture to OutputStream-> write the CAPTCHA string to TempData.

The difference between saving in TempData and Session: TempData is passed only once, that is, after passing to the next action, the action code will be destroyed after execution, and the Session will be saved continuously, so it is more appropriate to use TempData for CAPTCHA.

/ 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 take a look at the effect of generating the verification code of the graph:

2. Sha256 encryption

Add a static method Sha256 (string plainText) to the Security class of the COmmon project

/ plaintext / ciphertext public static string Sha256 (string plainText) {SHA256Managed _ sha256 = new SHA256Managed (); byte [] _ cipherText = _ sha256.ComputeHash (Encoding.Default.GetBytes (plainText)); return Convert.ToBase64String (_ cipherText);}

IV. Registration

Add a registered view model in Ninesky.Web.Areas.Member.Models

Using System.ComponentModel.DataAnnotations;namespace Ninesky.Web.Areas.Member.Models {public class RegisterViewModel {/ username / [Required (ErrorMessage = "required")] [StringLength (20, MinimumLength = 4, ErrorMessage = "{2} to {1} characters")] [Display (Name = "username")] public string UserName {get; set } / display name / [Required (ErrorMessage = "required")] [StringLength (20, MinimumLength = 2, ErrorMessage = "{2} to {1} characters")] [Display (Name = "display name")] public string DisplayName {get; set } / password / / [Required (ErrorMessage= "required")] [Display (Name = "password")] [StringLength (20 minimumLengthreading 6) ErrorMessage = "{2} to {1} characters")] [DataType (DataType.Password)] public string Password {get; set } / confirm password / [Required (ErrorMessage = "required")] [Compare ("Password", ErrorMessage = "password inconsistency")] [Display (Name = "confirm password")] [DataType (DataType.Password)] public string ConfirmPassword {get; set } / mailbox / / [Required (ErrorMessage= "required")] [Display (Name = "mailbox")] [DataType (DataType.EmailAddress,ErrorMessage= "Email format is incorrect")] public string Email {get; set } / CAPTCHA / / [Required (ErrorMessage = "required")] [StringLength (6, MinimumLength = 6, ErrorMessage = "CAPTCHA incorrect")] [Display (Name = "CAPTCHA")] public string VerificationCode {get; set;}

Add Register () action to UserController and return the strongly typed (RegisterViewModel) view directly

/ register / 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 () user Registration @ Html.ValidationSummary (true) @ Html.LabelFor (model = > model.UserName, new {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.UserName) @ Html.ValidationMessageFor (model = > model.UserName) @ Html.LabelFor (model = > model.DisplayName New {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.DisplayName) @ Html.ValidationMessageFor (model = > model.DisplayName) @ Html.LabelFor (model = > model.Password, new {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.Password) @ Html.ValidationMessageFor (model = > model.Password) @ Html.LabelFor (model = > model.ConfirmPassword New {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.ConfirmPassword) @ Html.ValidationMessageFor (model = > model.ConfirmPassword) @ Html.LabelFor (model = > model.Email, new {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.Email) @ Html.ValidationMessageFor (model = > model.Email) @ Html.LabelFor (model = > model.VerificationCode New {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.VerificationCode)

@ Html.ValidationMessageFor (model = > model.VerificationCode) I agree with the user Registration Agreement} $("# verificationcode") .click (function () {$("# verificationcode") .attr ("src", "@ Url.Action (" VerificationCode ")?" + new Date ();}) @ section Scripts {@ Scripts.Render ("~ / bundles/jqueryval")}

Then add public ActionResult Register (RegisterViewModel register) to the user controller to process 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", "user name already exists") Else {User _ user = new User () {UserName = register.UserName, / / 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 problem Status = 0, RegistrationTime = System.DateTime.Now}; _ user = userService.Add (_ user) If (_ user.UserID > 0) {return Content ("registered successfully!") ; / / AuthenticationManager.SignIn ();} else {ModelState.AddModelError ("," Registration failed! ") ;} return View (register);}

Many of the contents related to the root user settings in the code are not considered first, and will be modified after the meeting when the user settings are completed. Return to the view and display an error when registration fails; return to view when registration is successful, and let the user log in directly after registration the next time you login. Let's see how it works.

Click to register and the registration is successful.

A simple user registration is completed, including CAPTCHA, sha256 encryption, registering the view model, verifying the data submitted by the user and saving. This is followed by user registration, which uses ClaimsIdentity and HttpContext.GetOwinContext (). Authentication.SignIn ()

At this point, the study on "how to achieve ASP.NET MVC5 website development user registration" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report