【转载】ASP.NET Core 存储session取不到值

原文:http://www.bubuko.com/infodetail-3469204.html

需要注释掉startup里面的

//services.Configure<CookiePolicyOptions>(options =>
//{
//    options.CheckConsentNeeded = context => true;
//    options.MinimumSameSitePolicy = SameSiteMode.None;
//});

还有configure里面的

//app.UseCookiePolicy();

重新生成运行项目后发现可以正常使用


.net core Session的使用(NuGet里先下载:Microsoft.AspNetCore.Mvc包): 

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RecommendEntity.Model.System;

namespace RecommendWeb.Common
{
    public class BaseController : Controller
    {
        public string SESSION_USER = "SESSION_USER";
        public void UserSetSession(User user)
        {
            SetSession(SESSION_USER, JsonConvert.SerializeObject(user));
        }
        public User UserGetSession()
        {
            string json = GetSession(SESSION_USER);
            if (!string.IsNullOrWhiteSpace(json))
            {
                return JsonConvert.DeserializeObject<User>(json);
            }
            else
            {
                return null;
            }
        }
        private void SetSession(string key, string value)
        {
            HttpContext.Session.SetString(key, value);
        }
        private string GetSession(string key)
        {
            var value = HttpContext.Session.GetString(key);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }
    }

}

    任意Controller 继承 BaseController 就能使用:

    public class RecommendController : BaseController
    {
        public IActionResult Index()
        {
            User loginUser = new User();
            loginUser = UserGetSession();//读取Session
            if (loginUser == null)
            {
                return Redirect("~/Home/Login");
            }
            if (string.IsNullOrWhiteSpace(loginUser.Name) || string.IsNullOrWhiteSpace(loginUser.Role))
            {
                return Redirect("~/Home/Login");
            }
            return View();
        }
    }


    其他:https://www.cnblogs.com/atree/p/netcore-session.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值