cookie的使用和记住密码

喜欢ヅ旅行 2022-05-09 10:40 233阅读 0赞

后台:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using WebApplication1.Models;
  7. namespace WebApplication1.Controllers
  8. {
  9. public class LoginController : Controller
  10. {
  11. // GET: Login
  12. public ActionResult Index()
  13. {
  14. //获取cookie
  15. HttpCookie getCookie = Request.Cookies["user"];
  16. userinfo user = new userinfo() { username = "",pwd = "",IsChecked="" };
  17. //判断cookie是否为null
  18. if (getCookie != null)
  19. {
  20. user.username = getCookie.Values["username"];
  21. user.pwd = getCookie.Values["pwd"];
  22. user.IsChecked = "checked";
  23. }
  24. return View(user);
  25. }
  26. [HttpPost]
  27. public ActionResult IsLogin(userinfo user)
  28. {
  29. //user.username = Request["username"];
  30. //user.pwd = Request["pwd"];
  31. //判断是否选中记住密码
  32. if (user.IsChecked == "on")
  33. {
  34. //创建一个cookie
  35. HttpCookie hc = new HttpCookie("user");
  36. hc.Values["username"] = user.username;
  37. hc.Values["pwd"] = user.pwd;
  38. hc.Values["IsChecked"] = user.IsChecked;
  39. hc.Expires = DateTime.Now.AddDays(2);//设置cookie过期时间
  40. Response.Cookies.Add(hc);//添加cookie到集合中
  41. }
  42. else
  43. {
  44. //获取cookie
  45. HttpCookie getCookie = Request.Cookies["user"];
  46. //判断cookie是否为null
  47. if (getCookie != null)
  48. {
  49. //让cookie过期
  50. Response.Cookies["user"].Expires = DateTime.Now.AddHours(-1);
  51. }
  52. }
  53. return Redirect("~/Login/Sucess");
  54. }
  55. public ActionResult Sucess()
  56. {
  57. return View();
  58. }
  59. }
  60. }

页面:

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. @model WebApplication1.Models.userinfo
  5. <link href="~/Content/bootstrap.css" rel="stylesheet" />
  6. <script src="~/Scripts/bootstrap.js"></script>
  7. <div class="row"></div>
  8. <div class="container">
  9. <form action="~/Login/IsLogin" method="post">
  10. <div class="col-md-12">
  11. <div class="col-md-5"></div>
  12. <div class="col-md-2">
  13. <div class="form-group">
  14. <input type="text" name="username" id="username" value="@Model.username" />
  15. </div>
  16. <div></div>
  17. <div class="form-group">
  18. <input type="password" name="pwd" id="pwd" value="@Model.pwd"/>
  19. </div><div class="checkbox">
  20. <label>
  21. <input type="checkbox" name="IsChecked" id="IsChecked" @Model.IsChecked > 记住密码
  22. </label>
  23. </div>
  24. <div class="form-group">
  25. <input type="submit" name="sub" id="sub" value="登录" />
  26. </div>
  27. </div>
  28. <div class="col-md-5"></div>
  29. </div>
  30. </form>
  31. </div>

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读