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

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

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

NuGet安装

Microsoft.AspNetCore.Http.Abstractions

1.接口

cs 复制代码
public interface IUserService
{
    Task<OMUserInfo> GetUserInfoAsync(string token);
    Task<OMUserInfo> GetCurrentUserAsync();
}

2.用户对象

cs 复制代码
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.实现

cs 复制代码
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

cs 复制代码
 // 添加HttpContext访问器
 builder.Services.AddHttpContextAccessor();
 //注册用户服务
 // 注册Redis服务(使用之前实现的IRedisService)
 builder.Services.AddStackExchangeRedisCache(options =>
 {
     options.Configuration = builder.Configuration.GetConnectionString("Redis");
 });

 builder.Services.AddScoped<IUserService, OMUserService>();

5.控制器中使用

cs 复制代码
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);
}
相关推荐
绝无仅有21 小时前
面试真实经历某商银行大厂Java问题和答案总结(七)
后端·面试·github
绝无仅有21 小时前
面试真实经历某商银行大厂缓存Redis问题和答案总结(一)
后端·面试·github
IT_陈寒1 天前
Python性能翻倍的5个冷门技巧:从GIL逃逸到内存视图的实战优化指南
前端·人工智能·后端
程序员爱钓鱼1 天前
Python编程实战 · 基础入门篇 | 第一个Python程序:Hello World
后端·python·编程语言
陈大鱼头1 天前
摸鱼搭子知乎你怎么了?访问抛出的 525 错误码是什么啊?
运维·后端·http
陈随易1 天前
不使用 Husky 和 Lint-staged,实现 Git 提交前自动格式化代码
前端·后端·程序员
凤山老林1 天前
SpringBoot 启动时执行某些操作的 8 种方式
java·开发语言·spring boot·后端
莹Innsane1 天前
重新认识 Golang 中的 json 编解码
后端
东百牧码人1 天前
MySqlConnection is already in use是什么原因
后端