今天 无意看到Asp.net Core中使用Session ,首先要使用Session就必须添加Microsoft.AspNetCore.Session包,默认Session是只能存去字节,所以如果你想存取string的,那么还的引入Microsoft.AspNetCore.Http.Extensions包,那么在Startup.cs的ConfigureServices方法里面添加      services.AddSession(); (在 services.AddMvc()之前),在Configure方法添加   app.UseSession(); ( app.UseMvc()之前) 这样就可以使用Session了,默认Session是字节方式,这里我们使用json来序列化对象:

 public static class SessionExtensions
{
public static void Set(this ISession session, string key, object 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);
}
}

使用方式:

var city = new City { ID = 1, CountryCode = "123", Name = "city", District = "District test", Population = " Population test" };
HttpContext.Session.Set("city", city);
var c2 = HttpContext.Session.Get<City>("city");

如何保存到Redis中了?

首先需要添加对应的包Microsoft.Extensions.Caching.Redis,再调用AddDistributedRedisCache如下:

    public void ConfigureServices(IServiceCollection services)
{
// string mysqlConnectiong = Configuration.GetConnectionString("MySQL");
string redisConnectiong = Configuration.GetConnectionString("Redis");
services.AddSession();
services.AddDistributedRedisCache(option=>option.Configuration=redisConnectiong);
services.AddMvc();
}

配置如下:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"MySQL": "server=localhost;port=3306;uid=root;pwd=;database=word;charset=utf8;max pool size=1000;",
"Redis": "127.0.0.1:6379,abortConnect=false,connectRetry=3,connectTimeout=3000,defaultDatabase=1,syncTimeout=3000,version=3.2.1,responseTimeout=3000"
}
}

这样Session就可以保存到Redis了。

缓存的使用也很简单

IDistributedCache Cache;
public ValuesController(IDistributedCache cache) {
Cache = cache;
} Cache.SetString("test", "Gavin");
var vc = Cache.GetString("test");

我们在项目类库如何读配置文件

public class ConfigurationManager
{
/*
Microsoft.Extensions.Options.ConfigurationExtensions
Microsoft.Extensions.Configuration.Abstractions
Microsoft.AspNetCore.Http.Extensions
  Microsoft.Extensions.DependencyInjection
*/
static IConfiguration Configuration; static ConfigurationManager()
{
var baseDir = AppContext.BaseDirectory;
Configuration = new ConfigurationBuilder()
.SetBasePath(baseDir)
.Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = true })
.Build();
} public static T GetAppSettings<T>(string key) where T : class, new()
{
var appconfig = new ServiceCollection()
.AddOptions()
.Configure<T>( Configuration.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
} } public class ConnectionStrings
{
public string MySQL { set; get; }
public string Redis { set; get; }
}

单独访问Redis:

public class CityService
{
/*
* StackExchange.Redis
*/
static IDatabase redis;
static object lobject = new object();
public CityService()
{
if (redis == null)
{
lock (lobject)
{
if (redis == null)
{
var connection = ConfigurationManager.GetAppSettings<ConnectionStrings>("ConnectionStrings");
ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(connection.Redis);
redis = connectionMultiplexer.GetDatabase();
}
}
} } public IDatabase Redis { get { return redis; } }
}

读取MySql

  public List<City> TestDB()
{
/*MySql.Data*/
List<City> list = new List<City>();
using (MySqlConnection con = new MySqlConnection(MySqlConnectionStr))
{
MySqlCommand cmd = new MySqlCommand("SELECT ID, NAME,CountryCode, District, Population FROM city ;", con);
con.Open();
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new City
{
ID = reader.GetInt32("ID"),
Name = reader.GetString("NAME"),
CountryCode = reader.GetString("CountryCode"),
District = reader.GetString("District"),
Population = reader.GetString("Population")
});
}
}
}
return list;
}

参考  ASP.NET Core实现类库项目读取配置文件

ASP.NET Core实现强类型Configuration读取配置数据

4.3 可配置的分布式缓存(上)

Asp.net Core 使用Redis存储Session

Asp.net Core中使用Redis 来保存Session, 读取配置文件的更多相关文章

  1. ASP.NET Core教程:ASP.NET Core中使用Redis缓存

    参考网址:https://www.cnblogs.com/dotnet261010/p/12033624.html 一.前言 我们这里以StackExchange.Redis为例,讲解如何在ASP.N ...

  2. 如何在ASP.NET Core中使用Redis

    注:本文提到的代码示例下载地址> https://code.msdn.microsoft.com/How-to-use-Redis-in-ASPNET-0d826418 Redis是一个开源的内 ...

  3. ASP.NET Core 中jwt授权认证的流程原理

    目录 1,快速实现授权验证 1.1 添加 JWT 服务配置 1.2 颁发 Token 1.3 添加 API访问 2,探究授权认证中间件 2.1 实现 Token 解析 2.2 实现校验认证 1,快速实 ...

  4. 使用Redis Stream来做消息队列和在Asp.Net Core中的实现

    写在前面 我一直以来使用redis的时候,很多低烈度需求(并发要求不是很高)需要用到消息队列的时候,在项目本身已经使用了Redis的情况下都想直接用Redis来做消息队列,而不想引入新的服务,kafk ...

  5. Asp.net Core中使用Session

    前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. 元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Cor ...

  6. 在 ASP.NET CORE 中使用 SESSION

    Session 是保存用户和 Web 应用的会话状态的一种方法,ASP.NET Core 提供了一个用于管理会话状态的中间件.在本文中我将会简单介绍一下 ASP.NET Core 中的 Session ...

  7. 在 ASP.NET CORE 中使用 SESSION (转载)

    Session 是保存用户和 Web 应用的会话状态的一种方法,ASP.NET Core 提供了一个用于管理会话状态的中间件.在本文中我将会简单介绍一下 ASP.NET Core 中的 Session ...

  8. [转]Asp.net Core中使用Session

    本文转自:http://www.cnblogs.com/sword-successful/p/6243841.html 前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. ...

  9. C# 嵌入dll 动软代码生成器基础使用 系统缓存全解析 .NET开发中的事务处理大比拼 C#之数据类型学习 【基于EF Core的Code First模式的DotNetCore快速开发框架】完成对DB First代码生成的支持 基于EF Core的Code First模式的DotNetCore快速开发框架 【懒人有道】在asp.net core中实现程序集注入

    C# 嵌入dll   在很多时候我们在生成C#exe文件时,如果在工程里调用了dll文件时,那么如果不加以处理的话在生成的exe文件运行时需要连同这个dll一起转移,相比于一个单独干净的exe,这种形 ...

随机推荐

  1. java多线程快速入门(十三)

    死锁产生的原因(必须有两个线程.必须有多个锁.锁之间必须有引用的过程) package com.cppdy; class MyThread9 implements Runnable { private ...

  2. mvc中简单的异常记录

    说明:异常处理 1.1 在WebApp的Model中 添加异常处理类 继承于HandleErrorAttribute using System; using System.Collections.Ge ...

  3. <转>用 Java 技术创建 RESTful Web 服务

    转自:https://www.ibm.com/developerworks/cn/web/wa-jaxrs/#N1017E JAX-RS:一种更为简单.可移植性更好的替代方式 Dustin Amrhe ...

  4. c++ primer 学习杂记2【派生类到基类转换的可访问性】

    参考: http://blog.csdn.net/rehongchen/article/details/7930853 http://blog.csdn.net/ming_road/article/d ...

  5. 《剑指offer》-数组中只出现一次的数字

    /* 一个整型数组里除了两个数字之外,其他的数字都出现了两次.请写程序找出这两个只出现一次的数字. 思路: 如果是只有一个数字出现一次,那么所有数字做异或就得到结果: 现在有两个数字x,y分别出现一次 ...

  6. ThinkPHP3.1快速入门教程

    ThinkPHP3.1快速入门教程 http://www.thinkphp.cn/info/155.html   ------------------------------------------- ...

  7. [HDU] 5306 Gorgeous Sequence [区间取min&求和&求max]

    题解: 线段树维护区间取min求和求max 维护最小值以及个数,次小值 标记清除时,分情况讨论 当lazy>max1 退出 当max1>lazy>max2(注意不要有等号) 更新 否 ...

  8. my作业

    学号:2017xxxxxx 我是吴登峰,我的爱好是音乐,看电影,玩游戏! 我的码云个人主页是:https://gitee.com/fengaa 我的第一个项目地址是:https://gitee.com ...

  9. poj 1797 最大最小路段【dijkstra】 (经典)

    <题目链接> 题目大意: Hugo Heavy要从城市1到城市N运送货物,有M条道路,每条道路都有它的最大载重量,问从城市1到城市N运送最多的重量是多少. 解题分析: 感觉这道题用dijk ...

  10. UVA725 Division 除法【暴力】

    题目链接>>>>>> 题目大意:给你一个数n(2 <= n <= 79),将0-9这十个数字分成两组组成两个5位数a, b(可以包含前导0,如02345 ...