asp.netCore中 Cookie、Session使用

方法一、在.netCore中使用session首先需要在Startup中进行配置,

在 public IServiceProvider ConfigureServices(IServiceCollection services)中添加

//添加session
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
  // 设置 Session 过期时间15分钟
  options.IdleTimeout = TimeSpan.FromMinutes(15);
});

为方便统一获取,把Cookie和Session统一放到BaseController中

    public abstract class BaseController : Controller
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private ISession _session => _httpContextAccessor.HttpContext.Session;
        /// <summary>
        /// 设置本地cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>  
        /// <param name="minutes">过期时长,单位:分钟</param>      
        protected void SetCookies(string key, string value, int minutes = 30)
        {
            HttpContext.Response.Cookies.Append(key, value, new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(minutes)
            });
        }
        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key"></param>
        protected void DeleteCookies(string key)
        {
            HttpContext.Response.Cookies.Delete(key);
        }

        /// <summary>
        /// 获取cookie的value
        /// </summary>
        /// <param name="key"></param>
        /// <returns>返回对应的值</returns>
        protected string GetCookiesValue(string key)
        {
            HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }

        /// <summary>
        /// 添加Sesssion
        /// </summary>
        /// <param name="SesionStr"></param>
        /// <param name="Code"></param>
        public void SetSession(string SesionStr, string Code)
        {
            _session.SetString(SesionStr, Code);
        }

        /// <summary>
        /// 获取Session
        /// </summary>
        public string GetSession(string SesionStr)
        {
            string code = _session.GetString(SesionStr);
            return code;
        }
    }

在HomeController继承BaseController,并进行设置Cookies和Session

设置Cookies

 SetCookies("CookiesKey", cookieValue, 60);

获取Cookies

GetCookiesValue("CookiesKey");

方法二、设置和读取Session。

添加SessionExtensions类,使用序列化来保存Value

    using Microsoft.AspNetCore.Http;//需要添加此应用
//添加和获取Session
public static class SessionExtensions { public static void SetObjectAsJson<T>(this ISession session, string key, T value) { session.SetString(key, JsonConvert.SerializeObject(value)); } public static T GetObjectFromJson<T>(this ISession session, string key) { var value = session.GetString(key); return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value); } }

设置Session

//values可以为单一字符或者实体类
HttpContext.Session.SetObjectAsJson("SessionKey", UserModel);

获取Session

HttpContext.Session.GetObjectFromJson<UserModel>("SessionKey");

 

posted @ 2019-01-31 15:05  吃辣椒的小毛驴  阅读(3347)  评论(2编辑  收藏  举报