Net Core 中WebAPI有关 Session的设置,及获取

步骤一: 在Startup 文件中做相应的设置

ConfigureServices方法里添加

//ConfigureServices添加:

services.AddSession(options =>
            {
                options.Cookie.Name = ".AdventureWorks.Session";
                options.IdleTimeout = System.TimeSpan.FromSeconds(120);//设置session的过期时间
                options.Cookie.HttpOnly = true;//设置在浏览器不能通过js获得该cookie的值
            });
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpContextAccessor();
            #region 跨域
            services.AddCors(options =>
            options.AddPolicy("AllowSameDomain",
            builder => builder.WithOrigins().AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
            #endregion
//HttpContextAccessor 默认实现了它简化了访问HttpContext
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
 

Configure方法里面添加

app.UseSession();//UseSession配置在UseMvc之前

二  在具体的Control配置相应数据

1.   配置 并获取httpcontext

示例:

public class HomeController : Controller
    {
        private IHttpContextAccessor _accessor;
        public HomeController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        public IActionResult Index()
        {
            var httpcontext = _accessor.HttpContext;
            return View();
        }
    }

 

2.  写SessionHelper类

    public  class SessionHelper
    {
        private IHttpContextAccessor _accessor;

        private ISession _session ;
        private IRequestCookieCollection _requestCookie ;
        private IResponseCookies _responseCookie;
        public SessionHelper(HttpContext context)
        {
            _session = context.Session;
            _requestCookie = context.Request.Cookies;
            _responseCookie = context.Response.Cookies;
        }
        /// <summary>
        /// 设置session值
        /// </summary>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public  void SetSession(string key, string value)
        {
            var bytes = System.Text.Encoding.UTF8.GetBytes(value);
            _session.Set(key, bytes);
        }
        /// <summary>
        /// 获取Session值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public  string GetSession(string key)
        {
            Byte[] bytes;
            _session.TryGetValue(key, out bytes);
            var value = System.Text.Encoding.UTF8.GetString(bytes);

            if (string.IsNullOrEmpty(value))
            {
                value = string.Empty;
            }
            return value;
        }
        ///// <summary>
        ///// 设置本地cookie
        ///// </summary>
        ///// <param name="key"></param>
        ///// <param name="value"></param>
        ///// <param name="minutes">过期时间</param>
        //public void SetCookies(string key,string value,int day = 1)
        //{
        //    _responseCookie.Append(key, value, new CookieOptions
        //    {
        //        Expires = DateTime.Now.AddDays(day)
        //    }) ;
        //}
        //public void  DeleteCookies(string key)
        //{
        //    _responseCookie.Delete(key);
        //}
        //public string GetCookiesValue(string key)
        //{
        //    _requestCookie.TryGetValue(key, out string value);
        //    if (string.IsNullOrEmpty(value))
        //    {
        //        value = string.Empty;
        //    }
        //    return value;
        //}
    }

3.  方法里调用sessionHelper

                    var httpContext = _accessor.HttpContext;
                    SessionHelper session = new SessionHelper(httpContext);
                    string key = "王明";
                    string value = "2020年 大运年";
                    //设置session值
                    session.SetSession(key, value);
                    //获取session值
                    session.GetSession(key);

 

Net Core 中WebAPI有关 Session的设置,及获取

上一篇:阿里高级架构师分布式架构原理与设计终极方案流出,你与P7差别就在这里


下一篇:200道Java灵魂考题:全部掌握拿下阿里P7腾讯T3.2