作者的话:
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太吃性能了!