【橙子笔记】.NetCore--使用Session的常用具体方法

作者的话:
session在.net中用起来真的方便,但是在.net core最好别用!性能很差,这是趋势,用分布式技术+cookie搞定它最佳
使用session
Startup.cs中ConfigureServices申明:

services.AddSession();

Startup.cs中的Configure

 app.UseSession(); 

通常.net core是自带session的需要nuget下载,然后

using Microsoft.AspNetCore.Http

设置session代码:

 HttpContext.Session.SetString(key, value);

获取session代码:

HttpContext.Session.GetString(key);

注意,在.net core mvc中session无法在前端使用,如果要使用的话
Startup.cs中ConfigureServices申明:

 services.AddHttpContextAccessor();

在view试图插入

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor  _httpContextAccessor

在前端的试图使用session

_httpContextAccessor.HttpContext.Session.SetString(key,value)
_httpContextAccessor.HttpContext.Session.GetString(key)

注意,在.net core 中session无法接收对象,如果要接收的话
写一个类封装一下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace CC.YiCraftCore.Repository
{
    public static class SessionExtensionsHelper
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }
}

调用方法
设置session

SessionExtensionsHelper.Set<T>(HttpContext.Session,key, 类型为T的对象)

得到session

SessionExtensionsHelper.Get<T>(HttpContext.Session, key)

最后:
好麻烦啊
.net session[key]=value直接调用不香吗?管他是什么都可以往里面装!
不!
少用session!这就是一种趋势,session太吃性能了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值