Continuing from the previous article: C# ASP.NET Core Web
API Identity Authorization (JWT) Verification (1)
There is not much to say about building the Redis service, you can do it yourself: Xiaopi (phpstudy) is used for the windows platform, and pagoda is used for the linux platform, which is very convenient to build.
Right-click on the project, select Manage NuGet Packages, and add StackExchange.Redis:
Open the appsettings.json configuration file and add the following configuration:
"Redis": {
"Default": {
"Connection": "127.0.0.1:6379,password=d0d493hGlqePd2Tn", //redis连接地址,端口号,密码
"InstanceName": "local", //实例名
"DefaultDB": "8" //Db8数据库
}
}
Add the RedisHelper.cs class in the Common folder:
The complete code is as follows:
using StackExchange.Redis;
using System.Collections.Concurrent;
namespace TestApi.Common
{
/// <summary>
/// redis类
/// </summary>
public class RedisHelper : IDisposable
{
//连接字符串
private string _connectionString;
//实例名称
private string _instanceName;
//默认数据库
private int _defaultDB;
private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
/// <summary>
/// 初始化
/// </summary>
/// <param name="connectionString"></param>
/// <param name="instanceName"></param>
/// <param name="defaultDB"></param>
public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
{
_connectionString = connectionString;
_instanceName = instanceName;
_defaultDB = defaultDB;
_connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
}
/// <summary>
/// 获取ConnectionMultiplexer
/// </summary>
/// <returns></returns>
private ConnectionMultiplexer GetConnect()
{
return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
}
/// <summary>
/// 获取redis数据库
/// </summary>
/// <returns></returns>
public IDatabase GetDatabase()
{
return GetConnect().GetDatabase(_defaultDB);
}
/// <summary>
///
/// </summary>
/// <param name="configName"></param>
/// <param name="endPointsIndex"></param>
/// <returns></returns>
public IServer GetServer(string? configName = null, int endPointsIndex = 0)
{
var confOption = ConfigurationOptions.Parse(_connectionString);
return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
}
/// <summary>
///
/// </summary>
/// <param name="configName"></param>
/// <returns></returns>
public ISubscriber GetSubscriber(string? configName = null)
{
return GetConnect().GetSubscriber();
}
/// <summary>
///
/// </summary>
public void Dispose()
{
if (_connections != null && _connections.Count > 0)
{
foreach (var item in _connections.Values)
{
item.Close();
}
}
}
}
}
Add service dependencies in the Program.cs class
#region 配置Redis
// 配置Redis 注入类似于配置数据库连接字符串
var section = builder.Configuration.GetSection("Redis:Default");
// 连接字符串
string _connectionString = section.GetSection("Connection").Value;
// 实例名称
string _instanceName = section.GetSection("InstanceName").Value;
// 默认数据库
int _defaultDB = int.Parse(section.GetSection("DefaultDB").Value ?? "0");
builder.Services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));
#endregion
Test use, use in the controller interface, open UserInfoController.cs:
Add the following code:
Full code:
using Microsoft.AspNetCore.Mvc;
using TestApi.Common;
using TestApi.Models;
namespace TestApi.Controllers
{
[Route("[controller]/[action]")]
[ApiController]
public class UserInfoController : ControllerBase
{
private readonly JwtHelper _jwt;
private readonly RedisHelper _redis;
/// <summary>
/// 初始化
/// </summary>
/// <param name="jwtHelper"></param>
public UserInfoController(JwtHelper jwtHelper, RedisHelper redis)
{
_jwt = jwtHelper;
_redis = redis;
}
/// <summary>
/// 获取Token
/// </summary>
/// <returns></returns>
[HttpPost]
public IActionResult GetToken(UserInfo user)
{
//参数验证等等....
if (string.IsNullOrEmpty(user.UserName))
{
return Ok("参数异常!");
}
//这里可以连接mysql数据库做账号密码验证
//这里可以做Redis缓存验证等等
_redis.GetDatabase().StringSet("Name", user.UserName);// 往Redis里面存入数据
string name = _redis.GetDatabase().StringGet("Name");// 从Redis里面取数据
//这里获取Token,当然,这里也可以选择传结构体过去
var token = _jwt.CreateToken(user.UserName, user.PhoneNumber);
return Ok(token);
}
/// <summary>
/// 获取自己的详细信息,其中 [Authorize] 就表示要带Token才行
/// </summary>
/// <returns></returns>
[HttpPost]
[Authorize]
public IActionResult GetSelfInfo()
{
//执行到这里,就表示已经验证授权通过了
/*
* 这里返回个人信息有两种方式
* 第一种:从Header中的Token信息反向解析出用户账号,再从数据库中查找返回
* 第二种:从Header中的Token信息反向解析出用户账号信息直接返回,当然,在前面创建Token时,要保存进使用到的Claims中。
*/
return Ok("授权通过了!");
}
}
}
Then you can F5 to do the test.
The next article will introduce the use of MySQL:
C# ASP.NET Core Web API MySQL Tutorial (3) - Programmer Sought