Asp.net Core中使用Redis 来保存Session, 读取配置文件
今天 无意看到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实现强类型Configuration读取配置数据
Asp.net Core中使用Redis 来保存Session, 读取配置文件的更多相关文章
- ASP.NET Core教程:ASP.NET Core中使用Redis缓存
参考网址:https://www.cnblogs.com/dotnet261010/p/12033624.html 一.前言 我们这里以StackExchange.Redis为例,讲解如何在ASP.N ...
- 如何在ASP.NET Core中使用Redis
注:本文提到的代码示例下载地址> https://code.msdn.microsoft.com/How-to-use-Redis-in-ASPNET-0d826418 Redis是一个开源的内 ...
- ASP.NET Core 中jwt授权认证的流程原理
目录 1,快速实现授权验证 1.1 添加 JWT 服务配置 1.2 颁发 Token 1.3 添加 API访问 2,探究授权认证中间件 2.1 实现 Token 解析 2.2 实现校验认证 1,快速实 ...
- 使用Redis Stream来做消息队列和在Asp.Net Core中的实现
写在前面 我一直以来使用redis的时候,很多低烈度需求(并发要求不是很高)需要用到消息队列的时候,在项目本身已经使用了Redis的情况下都想直接用Redis来做消息队列,而不想引入新的服务,kafk ...
- Asp.net Core中使用Session
前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. 元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Cor ...
- 在 ASP.NET CORE 中使用 SESSION
Session 是保存用户和 Web 应用的会话状态的一种方法,ASP.NET Core 提供了一个用于管理会话状态的中间件.在本文中我将会简单介绍一下 ASP.NET Core 中的 Session ...
- 在 ASP.NET CORE 中使用 SESSION (转载)
Session 是保存用户和 Web 应用的会话状态的一种方法,ASP.NET Core 提供了一个用于管理会话状态的中间件.在本文中我将会简单介绍一下 ASP.NET Core 中的 Session ...
- [转]Asp.net Core中使用Session
本文转自:http://www.cnblogs.com/sword-successful/p/6243841.html 前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. ...
- 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,这种形 ...
随机推荐
- 使用@font-family时各浏览器对字体格式(format)的支持情况
说到浏览器对@font-face的兼容问题,这里涉及到一个字体format的问题,因为不同的浏览器对字体格式支持是不一致的,这样大家有必要了解一下,各种版本的浏览器支持什么样的字体,前面也简单带到了有 ...
- 使用caffe模型测试图片(python接口)
1.加载相关模块 1.1 加载numpy import numpy as np 1.2 加载caffe 有两种方法. 方法一(静态导入): 找到当前环境使用的python的site-packages目 ...
- poj2442 堆应用
#include <cstdio> #include <cstring> #include <string> #include <vector> #in ...
- 微信公众号开发JS-SDK(1.2)
概述 微信js-SDK是微信公众平台面向网页开发者提供的基于微信内的网页开发工具包. 通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照.选图.语音.位置等手机系统的能力,同时可以直接使用微 ...
- 步步为营-69-Razor基础
作用:进一步将HTML代码和C#代码进行解耦 1.1 引用程序集(RazorEngine.dll,System.Web.Razor.dll) 1.1.1 可以从http://razorengine.c ...
- flex布局简介
一.概述 浮动在移动布局中不再重要,flex盒模型越来越重要. flexbox经历过三个版本,主要区别是2009年到2012年之间的语法变化. 最新的语法和现在规范是同步的(例display:flex ...
- C# Winform OpenFileDialog 控件
OpenFileDialog控件又称打开文件对话框,主要用来弹出Windows中标准的[打开文件]对话框. OpenFileDialog控件的常用属性如下. (1)Title属性:用来获取或设置对话框 ...
- BZOJ2333 [SCOI2011]棘手的操作 堆 左偏树 可并堆
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ2333 题意概括 有N个节点,标号从1到N,这N个节点一开始相互不连通.第i个节点的初始权值为a[i ...
- python str,list,tuple转换
1. str转listlist = list(str) 2. list转strstr= ''.join(list) 3. tuple list相互转换tuple=tuple(list)list=l ...
- POJ 2407 Relatives【欧拉函数】
<题目链接> 题目大意: Given n, a positive integer, how many positive integers less than n are relativel ...