文章出處

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);
        }

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()