当前位置: 首页 > news >正文

Asp.net Core 通过依赖注入的方式获取用户

思路:Web项目中,需要根据当前登陆的用户,查询当前用户所属的数据、添加并标识对象等。根据请求头Authorization 中token,获取Redis中存储的用户对象。

本做法需要完成 基于StackExchange.Redis 配置,参考:Asp.Net Core基于StackExchange Redis 缓存-CSDN博客

NuGet安装

Microsoft.AspNetCore.Http.Abstractions

1.接口

public interface IUserService
{Task<OMUserInfo> GetUserInfoAsync(string token);Task<OMUserInfo> GetCurrentUserAsync();
}

2.用户对象

public class OMUserInfo
{public Guid UId { get; set; }public string UName { get; set; }public string TrueName { get; set; }public string Mobile { get; set; }public bool IsAdmin { get; set; }public string Department { get; set; }public string UType { get; set; }public string OId { get; set; }public string Token { get; set; }public DateTime ExpireDateTime { get; set; }
}

3.实现

public class OMUserService : IUserService
{private readonly IRedisService _redisService;private readonly IHttpContextAccessor _httpContextAccessor;public OMUserService(IRedisService redisService,IHttpContextAccessor httpContextAccessor){_redisService = redisService;_httpContextAccessor = httpContextAccessor;}public async Task<OMUserInfo> GetCurrentUserAsync(){var token = GetTokenFromHeader();if (string.IsNullOrEmpty(token))return null;return await GetUserInfoAsync(token);}public async Task<OMUserInfo> GetUserInfoAsync(string token){var userKey = $"user:{token}";return await _redisService.StringGetAsync<OMUserInfo>(userKey);}private string GetTokenFromHeader(){var authHeader = _httpContextAccessor.HttpContext?.Request.Headers["Authorization"].ToString();return authHeader?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);}
}

4.注入

Asp.Net Core项目Nuget添加 Microsoft.Extensions.Caching.StackExchangeRedis

 // 添加HttpContext访问器builder.Services.AddHttpContextAccessor();//注册用户服务// 注册Redis服务(使用之前实现的IRedisService)builder.Services.AddStackExchangeRedisCache(options =>{options.Configuration = builder.Configuration.GetConnectionString("Redis");});builder.Services.AddScoped<IUserService, OMUserService>();

5.控制器中使用

private readonly IRedisService _redis;
private readonly IUserService _userService;
public TestController(IRedisService redis, IUserService userService) 
{_redis = redis;_userService = userService;
}[HttpGet("string")]
public async Task<IActionResult> TestString()
{var user = await _userService.GetCurrentUserAsync();Console.WriteLine(user.TrueName);await _redis.StringSetAsync("anna","多慢慢");var result = await _redis.StringGetAsync<string>("anna");return Ok(result);
}

http://www.lqws.cn/news/125029.html

相关文章:

  • Facebook接入说明
  • CentOS 7 修改为静态 IP 地址完整指南
  • sql入门语句-案例
  • .NET 9中的异常处理性能提升分析:为什么过去慢,未来快
  • .Net Framework 4/C# 集合和索引器
  • PocketFlow 快速入门指南
  • .NET 原生驾驭 AI 新基建实战系列(三):Chroma ── 轻松构建智能应用的向量数据库
  • 【openssl】升级为3.3.1,避免安全漏洞
  • SSL安全证书怎么安装?
  • 大模型高效提示词Prompt编写指南
  • Pluto论文阅读笔记
  • stress-ng 服务器压力测试的工具学习
  • GlobalSign、DigiCert、Sectigo三种SSL安全证书有什么区别?
  • 尝试使用gocryptfs实现大模型加密部署
  • Linux网络协议栈:从Socket到网卡的星辰大海
  • 搭建nginx的负载均衡
  • JavaScript中的正则表达式:文本处理的瑞士军刀
  • 循序渐进kubernetes之Lens
  • Elasticsearch中的语义搜索(Semantic Search)介绍
  • Appium+python自动化(九)- 定位元素工具
  • bug:undefined is not iterable (cannot read property Symbol(Symbol.iterator))
  • PowerBI企业运营分析—全动态盈亏平衡分析
  • 技术文章大纲:SpringBoot自动化部署实战
  • 分析Web3下数据保护的创新模式
  • Windows系统目录规范与最佳实践
  • KrillinAI:视频跨语言传播的一站式AI解决方案
  • LabVIEW与Modbus/TCP温湿度监控系统
  • 水利流速监测工程中的雷达流速仪
  • MySQL 关联查询速查笔记
  • 嵌入式学习笔记 - freeRTOS任务设计要点