欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > Asp.net Core 通过依赖注入的方式获取用户

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

2025/6/10 0:16:04 来源:https://blog.csdn.net/u012839776/article/details/148433460  浏览:    关键词: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);
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词