C#通过Cookie记住登录信息

MVC前台代码

@{
    ViewBag.Title = "Index";
}


Index

用户名
密码
记住密码  
 

MVC后台代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication100.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            HttpCookie cookie = Request.Cookies["UserInfoRemember"];
            Student Model = new Student();
            if (cookie != null)
            {
                Model.UserName = cookie["UserName"].ToString();
                Model.Password = cookie["Password"].ToString();
            }
            return View(Model);
        }
        /// 
        ///登录
        /// 
        /// 用户名
        /// 密码
        /// 是否记住用户名、密码
        [HttpPost]
        public bool UserLogin(string UserName, string Password, bool DoRemember)
        {
            if (DoRemember)
            {
                HttpCookie cookie = new HttpCookie("UserInfoRemember");
                cookie.HttpOnly = true;
                cookie["UserName"] = UserName;
                cookie["Password"] = Password;
                cookie.Expires = DateTime.MaxValue;
                Response.Cookies.Add(cookie);
            }
            else
            {
                HttpCookie cookie = Request.Cookies["UserInfoRemember"];
                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now.AddDays(-1);//立即过期
                    Response.Cookies.Add(cookie);//重新写入才能使Cookies["userinfo"]失效*/   
                }
            }
            return true;
        }
    }
    public class Student
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}


你可能感兴趣的:(c#,web)