如何从.Net Core中的HttpContext访问声明?

Rav*_*avi 5 c# asp.net-identity asp.net-core identityserver4 asp.net-core-3.1

使用下面的代码通过自定义声明进行登录,并且工作正常。

    private async Task SignInAsync(ApplicationUser user)
    {
        var claims = await _claimsPrincipalFactory.CreateAsync(user);

        claims.Identities.First().AddClaims(new[]
        {
            new Claim("xxx", "111"),
            new Claim("yyy", "222")
        });

        await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, claims);
    }
Run Code Online (Sandbox Code Playgroud)

但是当尝试在服务中使用 HttpContext 进行访问时,如下所示

var claims = HttpContext.User.Identities.FirstOrDefault().Claims.ToList();
Run Code Online (Sandbox Code Playgroud)

它返回 0 项索赔。

请帮忙。

Rav*_*avi 0

最后这是工作代码。

        services.ConfigureApplicationCookie(options =>
        {
            options.Events.OnSignedIn = (context) =>
            {
                context.HttpContext.User = context.Principal;
                return Task.CompletedTask;
            };
        });
Run Code Online (Sandbox Code Playgroud)