zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    最大子序和
    Linux中判断hdfs文件是否存在
    Python判断字符串是否为字母或者数字
    win10+1060显卡安装anaconda+CUDA10.1+pytorch+cuDNN+tensorflow-gpu
    Anaconda3+python3环境下如何创建python2环境(win+Linux下适用,同一个anaconda下py2/3共存)
    教你上传本地代码到github
    vue源码学习-vnode的挂载和更新流程
    学习 vue 源码 -- 响应式原理
    instanceof 操作符实现原理解析
    webapp开发要点记录
  • 原文地址:https://www.cnblogs.com/for-easy-fast/p/12157664.html
Copyright © 2011-2022 走看看