在MVC 3中创建Cookie

P_A*_*A_1 4 asp.net asp.net-mvc asp.net-mvc-3

如何逐步创建cookie,

在用户单击"记住我"时存储用户登录ID和密码?选项

我打算在一定时间后杀掉这个cookie

Hac*_*ese 14

Cookie的创建方式与普通旧ASP.NET相同,只需访问即可Response.

        public ActionResult Login(string username, string password, bool rememberMe)
        {
            // validate username/password

            if (rememberMe)
            {
               HttpCookie cookie = new HttpCookie("RememberUsername", username);
               Response.Cookies.Add(cookie);
            }

            return View();

        }
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用的是Forms Auth,则可以使FormsAuth票证cookie保持不变:

        public ActionResult Login(string username, string password, bool rememberMe)
        {
            // validate username/password

            FormsAuthentication.SetAuthCookie(username, rememberMe);

            return View();

        }
Run Code Online (Sandbox Code Playgroud)

你可以读这样的cookie:

public ActionResult Index()
{
    var cookie = Request.Cookies["RememberUsername"];

    var username = cookie == null ? string.Empty : cookie.Value; // if the cookie is not present, 'cookie' will be null. I set the 'username' variable to an empty string if its missing; otherwise i use the cookie value

    // do what you wish with the cookie value

    return View();
}
Run Code Online (Sandbox Code Playgroud)

如果您正在使用窗体身份验证和用户登录,您可以访问他们的用户名是这样的:

public ActionResult Index()
{


    var username = User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty;

    // do what you wish with user name

    return View();
}
Run Code Online (Sandbox Code Playgroud)

可以解密和读取票证的内容.如果需要,您甚至可以在故障单中存储少量自定义数据.有关详细信息,请参阅此文章.