欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解.NET 6如何實(shí)現(xiàn)獲取當(dāng)前登錄用戶信息

 更新時(shí)間:2022年01月19日 14:18:37   作者:CODE4NOTHING  
這篇文章主要介紹了.NET 6在應(yīng)用開(kāi)發(fā)時(shí)是如何實(shí)現(xiàn)當(dāng)前登陸用戶信息獲取的,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下

需求

在前面的文章里使用.NET 6開(kāi)發(fā)TodoList應(yīng)用之領(lǐng)域?qū)嶓w創(chuàng)建原理和思路,我們留了一個(gè)坑還沒(méi)有填上,就是在數(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)文章

最新評(píng)論