MVC authentication 01-BASIC, Remote authentication

Source: Internet
Author: User

Original: MVC authentication 01-BASIC, Remote authentication

This article experiences MVC server side and client authentication. Mainly related to:
※ Basic Verification
※ Remote verification of 1 or more attributes and points of attention

Basic Experience

The creation of MVC4 's Internet project, which itself contains the basic model,views,controller.

-model Verification Features

Expand     Public classRegistermodel {[Required] [Stringlength (3, minimumlength = 2)]//Plus[Display (Name = "User name")] Public stringUserName {Get;Set; } [Required] [stringlength (errormessage = "{ 0} field minimum {2} characters, up to {1} characters", Minimumlength = 6)] [DataType (Datatype.password)] [Display (Name ="Password")] Public stringPassword {Get;Set; } [DataType (Datatype.password)] [Display (Name = "Confirm Password")] [Compare ("Password", errormessage ="The password and confirmation password do not match. ")] Public stringConfirmPassword {Get;Set; }    }

Part of the-homecontroller about registration

Expand[AllowAnonymous] PublicActionResult Register () {returnView (); }//        //POST:/account/register[HttpPost]        [AllowAnonymous] [Validateantiforgerytoken] PublicActionResult Register (Registermodel model) {if(modelstate.isvalid) {//Try to register a user                Try{Websecurity.createuserandaccount (model. UserName, model.                    Password); Websecurity.login (model. UserName, model. Password);returnRedirecttoaction ("Index", "Home"); }Catch(MembershipCreateUserException e) {Modelstate.addmodelerror ("", Errorcodetostring (E.statuscode)); }            }//If something goes wrong when we go to this step, re-display the form            returnView (model); }

-/home/register View

Expand@model mvcvalidation.models.registermodel@{viewbag.title = "Register";} @using(Html.BeginForm ())        {@Html. AntiForgeryToken () @Html. ValidationSummary () <fieldset> <legend> Registration Form </legend> <ol> <li> @Html. labelfor (M = m.username) @Html. Textboxfor (M                + m.username) </li> <li> @Html. labelfor (M = m.password) @Html. passwordfor (M = m.password) </li> <li> @Html. labelfor (M = > M.confirmpassword) @Html. passwordfor (M = m.confirmpassword) </li> </ol&        Gt <input type= "Submit"value="Register"/> </fieldset>} @section Scripts {@Scripts. Render ("~/bundles/jqueryval")}

Effect:

-Removal of client authentication

<appSettings>
<add key= "clientvalidationenabled" value= "false"/>
<add key= "unobtrusivejavascriptenabled" value= "false"/>
</appSettings>

Set the client-side validation-related property to False and find the validation much slower.

Experience remote Validation Properties

Sometimes, such as verifying that a user name exists, we want to send an asynchronous request to the controller.
The remote attribute is assigned to the attribute.

Expand     Public classRegistermodel {[Required] [Stringlength (6, minimumlength = 2)]//Plus[Display (Name = "User name")] [Remote ("Checkusername","Validate", errormessage ="Remote authentication of user name failed")] Public stringUserName {Get;Set; } [Required] [stringlength (errormessage = "{ 0} field minimum {2} characters, up to {1} characters", Minimumlength = 6)] [DataType (Datatype.password)] [Display (Name ="Password")] Public stringPassword {Get;Set; } [DataType (Datatype.password)] [Display (Name = "Confirm Password")] [System.ComponentModel.DataAnnotations.Compare ("Password", errormessage ="The password and confirmation password do not match. ")] Public stringConfirmPassword {Get;Set; }    }

Validate Controller

Expand         //The parameter username must be consistent with the attribute username in the view model public         jsonresult checkusername (  String userName)        {            boolfalse;            //Assuming that a username does not pass            if (UserName! = "demo")            {                true;            }            //remote Authentication is requested by the            get method return Json (Isvalidate, jsonrequestbehavior.allowget);        }


Attention:
The Remote Authentication controller method parameters must match the properties of the view model that require remote validation, but are not case sensitive.

Results:

-Remote validation of multiple properties at the same time

For example, we want to remotely verify username and email at the same time.
We can make a remote on one of the properties of the view model, and other properties that require remote validation are listed in Additionalfields.

public string UserName {get; set;}

[Remote ("Checkusername", "Validate", Additionalfields = "UserName", errormessage = "Remote Authentication failed")]
public string Email {get; set;}

Attention:
Additionalfields The fields listed are case-sensitive.

Remote authentication method for the corresponding controller:

Expand //the parameter username here, Email must be username with properties in view model, email is consistent, case insensitive  public  jsonresult Check            UserName (string  UserName, string  email) {            bool  isvalidate = false ;             //assume that a username does not pass  if  (UserName! = "demo " && Email! = "[email              protected]  ") {isvalidate = true ; } //remote authentication is a  return Json (Isvalidate, jsonrequestbehavior.allowget); }


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.