其他分享
首页 > 其他分享> > NetCore 使用Session和Cookie

NetCore 使用Session和Cookie

作者:互联网

Session

1.在 Startup: ConfigureServices 中添加一下代码

services.AddSession();

2.在 Startup: Configure 中添加一下代码

app.UseSession();

3.正常使用

            var sessionKeyName = "S-KeyName";
            var session = HttpContext.Session.GetString(sessionKeyName);
            if (string.IsNullOrWhiteSpace(session))
            {
                HttpContext.Session.SetString(sessionKeyName, DateTime.Now.ToString("yyyyMMdd-HHmmss"));
                session = HttpContext.Session.GetString(sessionKeyName);
            }

Cookie

1.使用

            var cookieKeyName = "C-KeyName";
            var cookie = HttpContext.Request.Cookies[cookieKeyName];
            if (string.IsNullOrWhiteSpace(cookie))
            {
                cookie = DateTime.Now.ToString("yyyyMMdd-HHmmss");
                HttpContext.Response.Cookies.Append(cookieKeyName, cookie);
            }

 

标签:session,NetCore,Session,Cookie,var,cookie,HttpContext,sessionKeyName
来源: https://www.cnblogs.com/CRobot/p/15741654.html