1 Creating an ASP. NET MVC Project
Add a AccountController class.
Public classAccountcontroller:controller {[HttpGet] PublicActionResult Login (stringRETURNURL) {viewbag.returnurl = RETURNURL;returnView (); } [HttpPost] PublicActionResult Login (stringUserName,stringPasswordstringRETURNURL) {if(Checklogin (userName, password)) {//Add notes//Save identity informationAccountmodel Modeluser =NewAccountmodel () {UserName = UserName, Password = Password};stringUserData = Jsonconvert.serializeobject (Modeluser);//Serialize user entityFormsAuthenticationTicket Ticket =NewFormsAuthenticationTicket (1, UserName, DateTime.Now, DateTime.Now.AddHours (1),false, UserData); HttpCookie Cookie =NewHttpCookie (Formsauthentication.formscookiename, Formsauthentication.encrypt (Ticket));//Encrypt identity information, save to CookieRESPONSE.COOKIES.ADD (Cookie);if(string. IsNullOrEmpty (RETURNURL)) {returnRedirect ("~/home/index"); }Else{returnRedirect (RETURNURL); } }Else{returnView ("Login",Newresultmodel<string> () {Code = 1, Message ="User name or password error"}); } } PublicActionResult Logout () {formsauthentication.signout ();returnRedirecttoaction ("Login"); }Private BOOLChecklogin (stringUserName,stringPassword) {returnMvcApplication.DBList.Any (n = n.username = = UserName && N.password = = Password); } }
2 Add a custom attribute to filter the identity login
Public classCheckloginattribute:actionfilterattribute { Public Override voidOnActionExecuting (ActionExecutingContext filtercontext) {//If identity information exists if(! HttpContext.Current.User.Identity.IsAuthenticated) {Contentresult Content =NewContentresult ();stringURL =string. Format ("{0}?returnurl={1}", Formsauthentication.loginurl, FILTERCONTEXT.HTTPCONTEXT.REQUEST.RAWURL); Content.content =string. Format ("<script type= ' text/javascript ' >alert (' Please login first! '); window.location.href= ' {0} ';</script> ', URL); Filtercontext.result = Content; }//else //{ //string[] Role = CheckLogin.Instance.GetUser (). Roles.split (', ');//Get all roles //if (! Role.contains (Code))//Verify Permissions // { //// verification does not pass //Contentresult Content = new Contentresult (); //Content.content = "<script type= ' text/javascript ' >alert (' permission validation does not pass! '); History.go ( -1);</script> "; //Filtercontext.result = Content; // } //}} }
3 Set up Web. config, be sure to add mode= "Forms"
<system.web> ... . <authentication mode="Forms"> <forms loginurl="~/account/login" name= ". Iamshop " ></forms> </authentication> ... </system.web>
4 where you need to add permission validation: Mark a [Checklogin] property
[Checklogin] public actionresult Index () { //Get login information Viewbag.username = User.Identity.Name; //Get Object //formsidentity ticket = (formsidentity) user.identity; HttpCookie Authcookie = Httpcontext.request.cookies[formsauthentication.formscookiename]; //get cookie FormsAuthenticationTicket Ticket = Formsauthentication.decrypt (Authcookie.value); //decryption //accountmodel account = (Accountmodel) jsonconvert.deserializeobject (ticket.userdata);//deserialization Accountmodel account= jsonconvert.deserializeobject<accountmodel> (ticket.userdata); Viewbag.accountname = account. UserName; Viewbag.password = account. Password; return View (); }
Online authentication Code A lot, reference to do after a note, need to use, according to the circumstances to modify the use.
ASP. NET MVC Cookie authentication