ASP.NET MVC项目演练:用户登录

ASP.NET MVC 基础入门 http://www.cnblogs.com/liunlls/p/aspnetmvc_gettingstarted.html

设置默认启动页面

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
            );
        }
    }

设置重定向配置(没有登录的匿名用户将重定向到配置的地址)

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880"></forms>
    </authentication>

设置控制器过滤器;Authorize特性也可以只设置方法;下面的代码中,如果用户没有登录,请求Home/UserCenter话会被定向到登录界面(Account/Login)

    //Authorize,过滤器(filter),禁止匿名访问
    [Authorize]
    public class HomeController : Controller
    {
        //允许匿名用户访问
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserCenter()
        {
            return View();
        }
    }

登录数据模型,用的是VS自动生成的,可以根据自己的需求定制,包括数据验证特性,可参考http://www.cnblogs.com/liunlls/p/aspnet_mvc_adding_validation.html

    public class LoginViewModel
    {
        [Required]
        [Display(Name = "账号")]
        public string Account { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "密码")]
        public string Password { get; set; }

        [Display(Name = "记住我?")]
        public bool RememberMe { get; set; }
    }

登录方法

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            //验证账号密码
            if (model.Account.Equals("admin") && model.Password.Equals("123456"))
            {
               
                string userData = new JavaScriptSerializer().Serialize(model);
                //验证票据
                var ticket = new FormsAuthenticationTicket(1, model.Account, DateTime.Now,DateTime.Now.AddDays(COOKIE_EXPIRES), false, userData, FormsAuthentication.FormsCookiePath);
                //加密
                string encrypt = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt);
                if (model.RememberMe)
                {
                    cookie.Expires = DateTime.Now.AddDays(COOKIE_EXPIRES);
                }
                //保存cookie
                Response.Cookies.Remove(cookie.Name);
                Response.Cookies.Add(cookie);

                if (string.IsNullOrEmpty(returnUrl))
                {
                    
                    return RedirectToAction("Index","Home");
                }
                else
                    return Redirect(returnUrl);
            }
            else
            {
                ModelState.AddModelError("", "无效的登录尝试。");
                return View(model);
            }
        }

注销用户方法

        public ActionResult LoginOut()
        {
            FormsAuthentication.SignOut();
            return Redirect(FormsAuthentication.LoginUrl);
        }
原文地址:https://www.cnblogs.com/liunlls/p/asp-net-mvc-login.html