MVC模式下具体实现登入笔记

1.mvc添加登入验证

   public class RequireLoginAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //redirect if not authenticated
            if (IdentityUser.UserId<=0)
            {
                //use the current url for the redirect
                string redirectOnSuccess =Uri.EscapeUriString(filterContext.HttpContext.Request.RawUrl);

                //send them off to the login page
                string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                filterContext.HttpContext.Response.Redirect(loginUrl, true);
            }
        }
    }

  2.把登入信息填好

  private void FillUserInfo(UserInfo etUserInfo)
        {
            Session.Clear();
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, etUserInfo.UserName,DateTime.Now, DateTime.Now.AddMinutes(WebConfiguration.GetSessionStateTimeout.Minutes), false, etUserInfo.Id + ";"+etUserInfo.PassWord+";", FormsAuthentication.FormsCookiePath);
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); //Hashed ticket
            Response.Cookies.Add(authCookie);
            //FormsAuthentication.SetAuthCookie(etUserInfo.UserName, false, authCookie.Path);
        }

3.再在需登入的操作前加 [RequireLogin]如

        [RequireLogin]
        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        public void Delete()

{

}

这样就可以实现登入限制的功能了

原文地址:https://www.cnblogs.com/scottpei/p/1597238.html