詳解.NET 6如何實(shí)現(xiàn)獲取當(dāng)前登錄用戶信息
需求
在前面的文章里使用.NET 6開發(fā)TodoList應(yīng)用之領(lǐng)域?qū)嶓w創(chuàng)建原理和思路,我們留了一個(gè)坑還沒有填上,就是在數(shù)據(jù)庫(kù)保存的時(shí)候,CreateUser和ModifiedUser我們當(dāng)時(shí)填的都是Anonymous,完成認(rèn)證的功能后,現(xiàn)在我們需要實(shí)現(xiàn)在保存數(shù)據(jù)庫(kù)的時(shí)候填入當(dāng)前登陸進(jìn)行操作的用戶名。
目標(biāo)
實(shí)現(xiàn)當(dāng)前登陸用戶信息獲取。
原理和思路
原理很簡(jiǎn)單,在認(rèn)證時(shí)拿到的Token里,payload中是包含登陸User的部分信息的,作為演示,我們需要想辦法獲取到用戶名信息,并在保存數(shù)據(jù)時(shí)填入相應(yīng)字段。為了獲取Token中包含的用戶信息,需要用到HttpContextAccessor對(duì)象。很顯然,需要一個(gè)新的接口和實(shí)現(xiàn)。
實(shí)現(xiàn)
創(chuàng)建當(dāng)前用戶獲取接口
在Application/Common/Interfaces中添加一個(gè)新的接口:
ICurrentUserService.cs
namespace TodoList.Application.Common.Interfaces;
public interface ICurrentUserService
{
string? UserName { get; }
}
這里我們?nèi)〉氖荱serName,是因?yàn)樵诜祷氐腡oken中包含UserName的信息,如果需要使用UserId或其他信息,需要在GetClaims中添加:
// 演示了返回用戶名和Role兩個(gè)claims
var claims = new List<Claim>
{
// Claims中包含UserName信息
new(ClaimTypes.Name, User!.UserName),
new(JwtRegisteredClaimNames.Iss, _jwtConfiguration.ValidIssuer ?? "TodoListApi"),
new(JwtRegisteredClaimNames.Aud, _jwtConfiguration.ValidAudience ?? "http://localhost:5050")
};
實(shí)現(xiàn)接口功能
在Api/Services中添加類實(shí)現(xiàn)接口:
CurrentUserService.cs
using System.Security.Claims;
using TodoList.Application.Common.Interfaces;
namespace TodoList.Api.Services;
public class CurrentUserService : ICurrentUserService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public CurrentUserService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
// 通過(guò)注入的IHttpContextAccessor獲取`HttpContext.User(ClaimsPrinciple)`中對(duì)應(yīng)的Claims信息
public string? UserName => _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.Name);
}
并在Program中添加依賴注入:
Program.cs
builder.Services.AddSingleton<ICurrentUserService, CurrentUserService>();
使用功能
接下來(lái)我們?nèi)バ薷腄bContext,需要先在構(gòu)造函數(shù)中注入:
TodoListDbContext.cs
private readonly ICurrentUserService _currentUserService;
public TodoListDbContext(
DbContextOptions<TodoListDbContext> options,
IDomainEventService domainEventService,
ICurrentUserService currentUserService) : base(options)
{
_domainEventService = domainEventService;
_currentUserService = currentUserService;
}
在SaveChangesAsync方法中修改:
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new())
{
foreach (var entry in ChangeTracker.Entries<AuditableEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedBy = _currentUserService.UserName;
entry.Entity.Created = DateTime.UtcNow;
break;
case EntityState.Modified:
entry.Entity.LastModifiedBy = _currentUserService.UserName;
entry.Entity.LastModified = DateTime.UtcNow;
break;
}
}
// 省略其他...
}
驗(yàn)證
啟動(dòng)Api項(xiàng)目,首先獲取Token,再用獲取到的Token去創(chuàng)建一個(gè)新的TodoList:

可以看到新創(chuàng)建的TodoList的用戶信息已經(jīng)獲取到了,為了確保數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)中,我們?nèi)?shù)據(jù)庫(kù)看一下:

總結(jié)
在本文中我們實(shí)現(xiàn)了如何從請(qǐng)求中獲取當(dāng)前登陸的用戶信息并保存到數(shù)據(jù)庫(kù)中。
到此這篇關(guān)于詳解.NET 6如何實(shí)現(xiàn)獲取當(dāng)前登錄用戶信息的文章就介紹到這了,更多相關(guān).NET 6獲取當(dāng)前登錄用戶信息內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c#使用Dataset讀取XML文件動(dòng)態(tài)生成菜單的方法
這篇文章主要介紹了c#使用Dataset讀取XML文件動(dòng)態(tài)生成菜單的方法,涉及C#使用Dataset操作XML文件的相關(guān)技巧,需要的朋友可以參考下2015-05-05
C#中驗(yàn)證sql語(yǔ)句是否正確(不執(zhí)行語(yǔ)句)
C#中驗(yàn)證sql語(yǔ)句是否正確(不執(zhí)行語(yǔ)句),需要的朋友可以參考一下2013-03-03
C#從foreach語(yǔ)句中枚舉元素看數(shù)組詳解
這篇文章主要給大家介紹了關(guān)于C#從foreach語(yǔ)句中枚舉元素看數(shù)組的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-05-05
C#根據(jù)http和ftp圖片地址獲取對(duì)應(yīng)圖片
這篇文章主要為大家詳細(xì)介紹了C#根據(jù)http和ftp圖片地址獲取對(duì)應(yīng)圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06

