MVC5----User Login and Verification code

Source: Internet
Author: User
Tags httpcontext

Write and record the learning process

Landing

Add Add in Models

 Public classLoginviewmodel {[Required (errormessage="*")] [Display (Name="Agency number")]         Public stringUserName {Get;Set; } [Required (ErrorMessage="*"] [DataType (Datatype.password)] [Display (Name="Password")]         Public stringPassWord {Get;Set; } [Required (ErrorMessage="*")] [Display (Name="Verification Code")]         Public stringcodeimg {Get;Set; }  Public stringerrormsg {Get;Set; } }

Views Code:

Which errormsg me to display the error message, other good methods do not know ...

@using (Html.BeginForm ("Login","Admin",New{ReturnUrl = Viewbag.returnurl}, FormMethod.Post,New{@class ="Form-horizontal", role ="form"}) {@Html. AntiForgeryToken () @Html. ValidationSummary (true)            <divclass="Login_mid_right"> <divclass="Login_mid_right_ul"> <divclass="Form-group">@Html. labelfor (M= M.username,New{@class ="col-md-3 Control-label" })                        <divclass="col-md-8">@Html. textboxfor (M= M.username,New{@class ="Form-control" })                        </div> @Html. validationmessagefor (M =m.username)</div> <divclass="Form-group">@Html. labelfor (M= M.password,New{@class ="col-md-3 Control-label" })                        <divclass="col-md-8">@Html. passwordfor (M= M.password,New{@class ="Form-control" })                        </div> @Html. validationmessagefor (M =M.password)</div> <divclass="Form-group">@Html. labelfor (M= M.codeimg,New{@class ="col-md-3 Control-label" })                        <divclass="col-md-4">@Html. textboxfor (M= M.codeimg,New{@class ="Form-control" })                                                    </div> @Html. validationmessagefor (M =m.codeimg)&nbsp;&nbsp; class="codeimg"title="can't see Clearly, click Refresh"alt="can't see Clearly, click Refresh"Src="/extensions/codeimg.ashx"onclick="javascript:this.src=this.src+ '? rnd= ' + math.random ();"/> </div> <divclass="Form-group"> <divclass="col-md-offset-3 col-md-9"> <input type="Submit"Value="Login" class="BTN-LG Btn-default"/> </div> </div> <divclass="Form-group"> <divclass="col-md-offset-3 col-md-9">@Html. validationmessagefor (M=m.errormsg)</div> </div> </div> </div>        }

Login verification, in the corresponding controllers:

 Public classAdmincontroller:controller {PrivateSimondbcontext db =NewSimondbcontext (); //        //GET:/admin/         PublicActionResult Index () {returnView (); }         PublicActionResult Login () {returnView (); }         PublicActionResult loginout () {session.clear ();            Session.Abandon (); returnRedirecttoaction ("Login","Admin"); } [HttpPost] PublicActionResult Login ([Bind (Include ="username,password,codeimg")] Loginviewmodel Login,stringreturnUrl) {            //return View ();            if(modelstate.isvalid) {inti =9; if(session["Checkcode"]. ToString ()! =Login. Codeimg.toupper ()) {Modelstate.addmodelerror ("errormsg","The verification code is not correct! "); }                Else{i=Authentication (login. UserName, Common.Helper.Encryption.SHA256 (login.                PassWord)); }                if(i = =0)                {                    //Cookies//HttpCookie cookie = new HttpCookie ("User"); //cookies. Values.add ("UserName", login.                    UserName); //Response.Cookies.Add (cookie); //Sessionsession["UserName"] =Login.                    UserName; returnRedirecttoaction ("Index","Admin"); }                Else if(i = =1) {Modelstate.addmodelerror ("errormsg","the user has been disabled! "); }                Else{modelstate.addmodelerror ("errormsg","The password or user name is wrong! "); }            }            returnView ("Login"); }        /// <summary>        ///Login Verification/// </summary>        /// <param name= "UserName" ></param>        /// <param name= "Pass" ></param>        /// <returns>        ///0: Login Successful///1: The user has been disabled///9: Wrong password or user name/// </returns>         Public intAuthentication (stringUserName,stringPass) {            intres =0; Adminmanager am= db. Adminmanager.singleordefault (c = C.username = =userName); if(AM = =NULL)            {                return 9; }            if(AM.) Flag! ="1")            {                return 1; }            if(AM.) PassWord! =Pass) {                return 9; }            returnRes; }    }

Do the landing, on other pages need to add to verify whether to login, add Userauthorizeattribute

 Public classUserauthorizeattribute:authorizeattribute {protected Override BOOLAuthorizecore (HttpContextBase HttpContext) {if(HttpContext = =NULL)            {                Throw NewArgumentNullException ("HttpContext"); }            if(httpcontext.current.session["UserName"] ==NULL)            {                               return false; }            return true; }    }

Add [Userauthorize] on a controller that requires validation

MVC5----User Login and Verification code

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.