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);
}
相关推荐
bobz9658 分钟前
Python 项目打包为 Windows exe 最好用的工具是哪个?
后端
用户214118326360220 分钟前
超算挑战赛实战!AI 一键生成中医药科普短视频,青少年轻松学药材
后端
还是鼠鼠26 分钟前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
追逐时光者32 分钟前
2025 年程序员必备 TOP 10 高效实用工具
后端
20181 小时前
Supabase migration 开发实践
后端
灵魂猎手1 小时前
3. MyBatis Executor:SQL 执行的核心引擎
java·后端·源码
Undoom1 小时前
虚拟机一站式部署Claude Code &可视化UI界面
后端
Asthenia04121 小时前
建好了表,还在手动写CRUD的xml?兄弟,真得学习MBG了!
后端
楽码2 小时前
底层技术SwissTable的实现对比
数据结构·后端·算法
m0_480502642 小时前
Rust 入门 泛型和特征-特征对象 (十四)
开发语言·后端·rust