SessionHelper.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Microsoft.AspNetCore.Http;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. using Microsoft.AspNetCore.Session;
  10. using Microsoft.AspNetCore.Http.Extensions;
  11. using Newtonsoft.Json;
  12. namespace YiSha.Util
  13. {
  14. public class SessionHelper
  15. {
  16. /// <summary>
  17. /// 写Session
  18. /// </summary>
  19. /// <typeparam name="T">Session键值的类型</typeparam>
  20. /// <param name="key">Session的键名</param>
  21. /// <param name="value">Session的键值</param>
  22. public void WriteSession<T>(string key, T value)
  23. {
  24. if (string.IsNullOrEmpty(key))
  25. {
  26. return;
  27. }
  28. IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
  29. hca?.HttpContext?.Session.SetString(key, JsonConvert.SerializeObject(value));
  30. }
  31. /// <summary>
  32. /// 写Session
  33. /// </summary>
  34. /// <param name="key">Session的键名</param>
  35. /// <param name="value">Session的键值</param>
  36. public void WriteSession(string key, string value)
  37. {
  38. WriteSession<string>(key, value);
  39. }
  40. /// <summary>
  41. /// 读取Session的值
  42. /// </summary>
  43. /// <param name="key">Session的键名</param>
  44. public string GetSession(string key)
  45. {
  46. try
  47. {
  48. if (string.IsNullOrEmpty(key))
  49. {
  50. return string.Empty;
  51. }
  52. IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
  53. if (hca?.HttpContext == null)
  54. return null;
  55. return hca?.HttpContext?.Session.GetString(key) as string;
  56. }
  57. catch
  58. {
  59. return string.Empty;
  60. }
  61. }
  62. /// <summary>
  63. /// 删除指定Session
  64. /// </summary>
  65. /// <param name="key">Session的键名</param>
  66. public void RemoveSession(string key)
  67. {
  68. if (string.IsNullOrEmpty(key))
  69. {
  70. return;
  71. }
  72. IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
  73. hca?.HttpContext?.Session.Remove(key);
  74. }
  75. }
  76. }