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 implement Asp.Mvc 2.0 user server authentication

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to achieve Asp.Mvc 2.0 user server authentication". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve Asp.Mvc 2.0 user server authentication".

For server-side authentication, you mainly call the class libraries in the System.ComponentModel.DataAnnotations namespace.

This time, we will take the registration page as an example to explain server-side verification, mainly to complete the following verification on the registration page

1. User name cannot be empty

two。 Password cannot be empty, password length cannot be less than 5 digits

3. The password and confirmation password must be the same.

4. The message must be formatted correctly

Let's take a look at the effect picture first.

To validate all fields in MVC, you only need to set validation rules in the MODEL layer.

1. User name authentication

To validate the user name, you only need to verify that the user name is not empty. Use the Required attribute to bind this attribute to the user name field of MODEL.

/ user name / / [DisplayName ("user name")] [Required (ErrorMessage= "user name cannot be empty!")] Public string UserName {get; set;}

The parameters in Required indicate specific prompts. If the user name is empty, a prompt that the user name cannot be empty appears on the foreground ASPX page. Of course, the wrong message should be displayed at the front desk. Use the m.UserName)% > tag to display the wrong message in the foreground

two。 Password authentication

Password authentication includes a password that cannot be empty and a password length limit.

Verify that the password is empty and verify that the user name is empty, using the Required attribute.

Verify that the length of the password uses the StringLength attribute.

/ password / / [DisplayName ("password")] [Required (ErrorMessage= "password cannot be empty")] [StringLength (10, ErrorMessage= "password length cannot be less than 5 digits", MinimumLength=5)] public string UserPwd {get; set;}

The first parameter of StringLength represents the maximum length of the password, and ErrorMessage represents the error message if the condition is not met.

MinimumLength represents the minimum length of input.

Of course, there must be a place at the front desk to display the error message. We use the following

M.UserPwd)% >

3. Verify that the password and confirm that the password is consistent

To verify that the password and confirm that the password is consistent, this is a little more complicated and requires us to customize the authentication rules. Custom validation rules we need to inherit the ValidationAttribute class. Then implement its isvaild method.

/ this custom class is used to verify passwords and confirm passwords must be consistent / [AttributeUsage (AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public class PwdMatch: ValidationAttribute {private object _ typeid = new object (); public string PWD {get; set;} / / password public string ConfirmPwd {get; set;} / / confirm password public PwdMatch (string pwd, string confirmPwd): base () {PWD = pwd ConfirmPwd = confirmPwd;} / return error message / public override string FormatErrorMessage (string name) {return ErrorMessage;} / rewrite TYPEID / public override object TypeId {get {return _ typeid } / the value of / value is actually the MODEL class / public override bool IsValid (object value) submitted by MODEL {PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (value); object originalValue = properties.Find (PWD, true) .GetValue (value); / / get the password object confirmValue = properties.Find (ConfirmPwd, true) .GetValue (value) / / get the value of the confirmation password return Object.Equals (originalValue, confirmValue);}} after the PwdMatch attribute class is created, you can mark it on the registration MODEL, and then when you submit the registration, you will verify [PwdMatch ("UserPwd", "ConfirPwd", ErrorMessage = "password"? With ®? Do you really recognize it? No? Is it a match? ")] Public class RegisterModel {}

The password on the first parameter table of PwdMatch, the name is the same as the password attribute in RegisterModel, the second field is the confirmation password, the name is the same as the confirmation password attribute of RegisterModel, and the last parameter is the error message.

Of course, the error message should also be displayed in the foreground, and a total list of error messages can be displayed in the foreground.

4. Mailbox verification

Mailbox verification is mainly mailbox format verification to verify whether the format meets the requirements. We can use the RegularExpressions attribute to verify the mailbox.

/ user mailbox / / [DisplayName ("mailbox")] / / [DataType (DataType.EmailAddress)] [Regular_Expression (@ "^\ w+ ((-\ w+) | (\.\ w+)) *\ @ [A-Za-z0-9] + ((\. | -) [A-Za-z0-9] +) *. [A-Za-z0-9] + $" ErrorMessage = "email format error")] public string Email {get Set;}

The first parameter is the regular expression validated by the mailbox, and the second parameter is the error message.

Display error messages on ASPX pages using m.Email)% >

The above is the verification of user registration information. Of course, when we submit the information, we need to determine whether the verification is passed or not. We use ModelState.IsValid to determine whether the verification is passed. TRUE means it is passed, and FALSE means it does not pass.

Model Code:

/ registered user MODEL / / [PwdMatch ("UserPwd", "ConfirPwd", ErrorMessage= "password does not match confirmation")] public class RegisterModel {/ username / [DisplayName ("username")] [Required (ErrorMessage= "username cannot be empty!")] Public string UserName {get; set;} / password / / [DisplayName ("password")] [Required (ErrorMessage= "password cannot be empty")] [StringLength (10, ErrorMessage= "password length cannot be less than 5 digits", MinimumLength=5)] public string UserPwd {get; set;} [DisplayName ("confirm password")] [Required (ErrorMessage= "confirm password cannot be empty!")] [StringLength (10, ErrorMessage = "confirm that the password length cannot be less than 5 digits", MinimumLength=5)] public string ConfirPwd {get; set } / [DisplayName ("mailbox")] / / [DataType (DataType.EmailAddress)] [Regular_Expression (@ "^\ w+ ((-\ w+) | (\.\ w+)) *\ @ [A-Za-z0-9] + ((\. |) [A-Za-z0-9] +) *. [A-Za-z0-9] + $" ErrorMessage = "email format error")] public string Email {get Set;} / this custom class is used to verify passwords and confirm passwords must be consistent / [AttributeUsage (AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public class PwdMatch: ValidationAttribute {private object _ typeid = new object (); public string PWD {get; set;} / / password public string ConfirmPwd {get; set } / / confirm password public PwdMatch (string pwd, string confirmPwd): base () {PWD = pwd; ConfirmPwd = confirmPwd;} / return the wrong message / public override string FormatErrorMessage (string name) {return ErrorMessage } / rewrite TYPEID / public override object TypeId {get {return _ typeid;}} / the value of / value is actually the MODEL class / public override bool IsValid (object value) {PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (value) submitted by MODEL. Object originalValue = properties.Find (PWD, true) .GetValue (value); / / get the password object confirmValue = properties.Find (ConfirmPwd, true) .GetValue (value); / / get the value return Object.Equals (originalValue, confirmValue) to confirm the password;}}

Foreground page code

Registration page / / $() .ready (function () {/ / $("# form1") .validate (/ / {/ / rules: / / {/ / UserName: / / {/ required: true / /}, / / UserPwd: / / {/ / required: true, / / minlength: 6 / /}) / / ConfirPwd: / / {/ / required: true, / / minlength: 6, / / equalTo: "# UserPwd" / /}, / / Email: / / {/ / email: true / /} /} / / messages: / / {/ UserName: / / {/ / required: "user name cannot be empty!" / / UserPwd: / / {/ / required: "password cannot be empty!", / / minlength: jQuery.format ("password length cannot be less than {0} characters!") / /} / / ConfirPwd: / / {/ / required: "confirm that the password cannot be empty!", / / minlength: jQuery.format ("confirm that the password length cannot be less than {0} characters!"), / / equalTo: "the two passwords are inconsistent!" / /} / / Email: / / {/ / email: "incorrect mailbox input format" / /} / /}, / / onkeyup: false / /}) / /})

M.UserName)% > m.UserPwd)% > m.ConfirPwd)% > m.Email)% > m.Email)% > m.Email)%

Controller code

/ / register and submit / / [HttpPost] public ActionResult Register (Models.RegisterModel model) {if (ModelState.IsValid) {/ / verify that bool result = false; if (! new Models.SqlHelper () .ExistUser (model)) {result = new Models.SqlHelper () .AddUser (model) } if (result) {/ / successfully go to the home page FormsService.SignIn (model.UserName, false); return RedirectToAction ("index");} else {/ / return the registration page ViewData ["msg"] = "failed to add user"; return View (model) }} else {/ / failed verification / / return to the registration page ViewData ["msg"] = "failed to add user"; return View (model) }} Thank you for reading, the above is the content of "how to implement Asp.Mvc 2.0 user server authentication". After the study of this article, I believe you have a deeper understanding of how to achieve Asp.Mvc 2.0 user server authentication, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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