123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using System;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.AspNetCore.Http;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web;
- using Microsoft.AspNetCore.Session;
- using Microsoft.AspNetCore.Http.Extensions;
- using Newtonsoft.Json;
- namespace YiSha.Util
- {
- public class SessionHelper
- {
- /// <summary>
- /// 写Session
- /// </summary>
- /// <typeparam name="T">Session键值的类型</typeparam>
- /// <param name="key">Session的键名</param>
- /// <param name="value">Session的键值</param>
- public void WriteSession<T>(string key, T value)
- {
- if (string.IsNullOrEmpty(key))
- {
- return;
- }
- IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
- hca?.HttpContext?.Session.SetString(key, JsonConvert.SerializeObject(value));
- }
- /// <summary>
- /// 写Session
- /// </summary>
- /// <param name="key">Session的键名</param>
- /// <param name="value">Session的键值</param>
- public void WriteSession(string key, string value)
- {
- WriteSession<string>(key, value);
- }
- /// <summary>
- /// 读取Session的值
- /// </summary>
- /// <param name="key">Session的键名</param>
- public string GetSession(string key)
- {
- try
- {
- if (string.IsNullOrEmpty(key))
- {
- return string.Empty;
- }
- IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
- if (hca?.HttpContext == null)
- return null;
- return hca?.HttpContext?.Session.GetString(key) as string;
- }
- catch
- {
- return string.Empty;
- }
- }
- /// <summary>
- /// 删除指定Session
- /// </summary>
- /// <param name="key">Session的键名</param>
- public void RemoveSession(string key)
- {
- if (string.IsNullOrEmpty(key))
- {
- return;
- }
- IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
- hca?.HttpContext?.Session.Remove(key);
- }
- }
- }
|