Net Core Session in WebAPI related settings, and access

Step a: accordingly provided Startup file

ConfigureServices method was added

// ConfigureServices added: 

services.AddSession (Options => 
            { 
                options.Cookie.Name = " .AdventureWorks.Session " ; 
                options.IdleTimeout = System.TimeSpan.FromSeconds ( 120 ); // set the expiration time of the session 
                options.Cookie. = the HttpOnly to true ; // set the browser can not obtain the value of the cookie js 
            }); 
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor> (); 
            services.AddHttpContextAccessor (); 
            #region cross-domain
            services.AddCors(options =>
            options.AddPolicy("AllowSameDomain",
            builder => builder.WithOrigins().AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
            #endregion
// HttpContextAccessor default implementation that simplifies access to the HttpContext 
services.AddSingleton <IHttpContextAccessor, HttpContextAccessor> ();
 

Configure method which added

app.UseSession (); // UseSession configuration before UseMvc

Two corresponding data in a particular configuration Control

1. Configure and get httpcontext

Example:

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

 

2. Write SessionHelper class

    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. The method in calling sessionHelper

                    var httpContext = _accessor.HttpContext; 
                    The SessionHelper session = new new (httpContext) The SessionHelper;
                     String Key = " Wang " ;
                     String value = " 2020 Year Grand Canal " ;
                     // set the session value 
                    session.SetSession (Key, value);
                     / / Get session value 
                    session.GetSession (key);

 

Guess you like

Origin www.cnblogs.com/for-easy-fast/p/12157664.html