using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nirvana.Common { public class WebHelper { #region cookie操作 /// /// 写cookie值 /// /// 名称 /// 值 /// 域名 public static void WriteCookie(string strName, string strValue, string domain = "") { if (!string.IsNullOrEmpty(domain)) { MyHttpContext.current.Response.Cookies.Append(strName, strValue, new Microsoft.AspNetCore.Http.CookieOptions { Domain = domain }); } else { MyHttpContext.current.Response.Cookies.Append(strName, strValue); } } /// /// 写cookie值 /// /// 名称 /// 值 /// 过期时间(分钟) /// 域名 public static void WriteCookie(string strName, string strValue, int expires, string domain = "") { if (!string.IsNullOrEmpty(domain)) { MyHttpContext.current.Response.Cookies.Append(strName, strValue, new Microsoft.AspNetCore.Http.CookieOptions { Domain = domain, Expires = DateTime.Now.AddMinutes(expires) }); } else { MyHttpContext.current.Response.Cookies.Append(strName, strValue, new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddMinutes(expires) }); } } /// /// 读cookie值 /// /// 名称 /// public static string GetCookie(string strName) { if (MyHttpContext.current !=null && MyHttpContext.current.Request.Cookies != null && !string.IsNullOrEmpty(MyHttpContext.current.Request.Cookies[strName])) { return MyHttpContext.current.Request.Cookies[strName]; } return ""; } /// /// 删除Cookie对象 /// /// Cookie对象名称 public static void RemoveCookie(string CookiesName) { if (MyHttpContext.current != null && MyHttpContext.current.Request.Cookies != null && !string.IsNullOrEmpty(MyHttpContext.current.Request.Cookies[CookiesName])) { MyHttpContext.current.Response.Cookies.Delete(CookiesName); } } #endregion #region Session操作 /// /// 写Session /// /// Session键值的类型 /// Session的键名 /// Session的键值 public static void WriteSession(string key, byte[] value) { if (key.IsEmpty()) return; MyHttpContext.current.Session.Set(key, value); } /// /// 写Session /// /// Session的键名 /// Session的键值 public static void WriteSession(string key, string value) { if (!string.IsNullOrEmpty(value)) { byte[] bt = Encoding.Default.GetBytes(value); WriteSession(key, bt); } } /// /// 读取Session的值 /// /// Session的键名 /// public static string GetSession(string key) { if (key.IsEmpty()) return string.Empty; if (MyHttpContext.current.Session == null) { return string.Empty; } var value = MyHttpContext.current.Session.GetString(key); return value; } /// /// 删除指定Session /// /// Session的键名 public static void RemoveSession(string key) { if (key.IsEmpty()) return; MyHttpContext.current.Session.Remove(key); } #endregion } }