You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.2 KiB

8 years ago
8 years ago
7 years ago
8 years ago
6 years ago
7 years ago
8 years ago
7 years ago
8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
7 years ago
8 years ago
7 years ago
8 years ago
7 years ago
8 years ago
  1. using System;
  2. using System.Web;
  3. namespace SiteServer.Utils
  4. {
  5. public static class CookieUtils
  6. {
  7. public static void SetCookie(string name, string value, TimeSpan expiresAt, bool isEncrypt = true)
  8. {
  9. SetCookie(new HttpCookie(name)
  10. {
  11. Value = value,
  12. Expires = DateUtils.GetExpiresAt(expiresAt),
  13. Domain = PageUtils.HttpContextRootDomain
  14. }, isEncrypt);
  15. }
  16. public static void SetCookie(string name, string value, DateTime expires, bool isEncrypt = true)
  17. {
  18. SetCookie(new HttpCookie(name)
  19. {
  20. Value = value,
  21. Expires = expires,
  22. Domain = PageUtils.HttpContextRootDomain
  23. }, isEncrypt);
  24. }
  25. public static void SetCookie(string name, string value, bool isEncrypt = true)
  26. {
  27. SetCookie(new HttpCookie(name)
  28. {
  29. Value = value,
  30. Domain = PageUtils.HttpContextRootDomain
  31. }, isEncrypt);
  32. }
  33. private static void SetCookie(HttpCookie cookie, bool isEncrypt)
  34. {
  35. cookie.Value = isEncrypt ? TranslateUtils.EncryptStringBySecretKey(cookie.Value) : cookie.Value;
  36. cookie.HttpOnly = false;
  37. if (HttpContext.Current.Request.Url.Scheme.Equals("https"))
  38. {
  39. cookie.Secure = true;//通过https传递cookie
  40. }
  41. HttpContext.Current.Response.Cookies.Add(cookie);
  42. }
  43. public static string GetCookie(string name)
  44. {
  45. if (HttpContext.Current.Request.Cookies[name] == null) return string.Empty;
  46. var value = HttpContext.Current.Request.Cookies[name].Value;
  47. return TranslateUtils.DecryptStringBySecretKey(value);
  48. }
  49. public static bool IsExists(string name)
  50. {
  51. return HttpContext.Current.Request.Cookies[name] != null;
  52. }
  53. public static void Erase(string name)
  54. {
  55. if (HttpContext.Current.Request.Cookies[name] != null)
  56. {
  57. SetCookie(name, string.Empty, DateTime.Now.AddDays(-1d));
  58. }
  59. }
  60. }
  61. }