gpt4 book ai didi

c# - ASP.NET Core 3.0 中获取当前经过身份验证的用户名的方法是什么?

转载 作者:行者123 更新时间:2023-12-03 14:24:22 25 4
gpt4 key购买 nike

我正在研究最新的 ASP.NET Core 3.0 Angular 模板。我需要知道的是我们如何在 ActionFilterAttribute 中获得经过身份验证的用户和用户名.
ClaimTypes.NameIdentifier返回当前用户 ID,和 ClaimTypes.Name返回为空的用户名。

这是我的代码:

enter image description here

哪里getUser有一个 UserIdd15f997a-6f65-4eb2-aecb-8b525361ae50
我还在 Startup 类中注册了 IHttpContextAccessor,如下所示:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));

services.AddDefaultIdentity<ApplicationUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();

services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

services.AddAuthentication()
.AddIdentityServerJwt();

//Database Setup
services.AddDbContext<HashooDBContext>(Configuration.GetConnectionString("DefaultConnection"));

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

services.AddControllersWithViews();
services.AddRazorPages();
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});

return ContainerSetup.InitializeWeb(Assembly.GetExecutingAssembly(), services);
}

Controller .cs:
[Authorize]
[ApiController]
[Route("api/[controller]/{companycode}")]
public class DashboardTransactionsController : ControllerBase
{
[CustomAuthorizationFilter("companycode")]
public string Get()
{
return "Welcome";
}
}

请让我知道我做错了什么?

最佳答案

您可以使用 IHttpContextAccessor

private readonly IHttpContextAccessor _httpContextAccessor;

public UserService(
IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

并获取用户名,您可以使用
_httpContextAccessor?.HttpContext?.User?.Identity?.Name;

或者
 _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

然后在您的 Startup.cs 中注册
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

关于c# - ASP.NET Core 3.0 中获取当前经过身份验证的用户名的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58473739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com