ASP.NET MVC 5 Example

ASP.NET MVC 5 Example

This is for cshtml code


@model Models.LoginViewModel
@{
    Layout = null;
}



    



This is Login controller with contain HttpPost, AllowAnonymous and ValidateAntiForgeryToken attribute.


        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                    // Encrypt the ticket and Create the cookie.
                    EncryptTicketCookies(model);
                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", Messages.InvalidUidPwd);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

This is used for user Authentication.
        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }

This is used for Forms Authentication Ticket.
        private static void EncryptTicketCookies(LoginViewModel model)
        {
            bool createPersistentCookie = false;
            string UserData = GetUserData(model);
            //// Create and tuck away the cookie
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now,   DateTime.Now.AddDays(1), createPersistentCookie, UserData);
            //// Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(authTicket);

            ////// Create the cookie.
            HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            System.Web.HttpContext.Current.Response.Cookies.Add(faCookie);
        }

This is used for RedirectToAction.
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }


ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^