当前用户在.NET 5中

发布于 2025-01-21 04:10:14 字数 449 浏览 0 评论 0原文

我正在使用 .NET 5 和 Identity 4。 当我想获取当前的 userId 或声明时,出现非常奇怪的错误。我无法在 Api 控制器中获取当前用户,但 Odata 控制器通常返回用户的数据和声明。

因此,我在两个控制器中键入以下代码:

 ClaimsPrincipal user = User;
        if (user != null)
        {
            string userId = user.Claims.Where(c => c.Type == "sub").FirstOrDefault()?.Value;
        }

在该示例中,我需要在 api 控制器中获取 userID。我在 odata 控制器中获取了 userID,没有任何问题。

我用谷歌搜索了很多时间,现在我没有想象,我向你寻求帮助。 有人遇到过类似的问题吗?

I am using .NET 5 and identity 4.
I have very strange error when I want to get current userId, or claims. I can't get current user in Api controller, but Odata controller return normally user's data and claims..

So, this code I type in both controllers:

 ClaimsPrincipal user = User;
        if (user != null)
        {
            string userId = user.Claims.Where(c => c.Type == "sub").FirstOrDefault()?.Value;
        }

In that example I need to get userID in api controller. I get userID in odata controller without any problem.

I google lot of time and now I don't have imagine and I ask you for help.
Has anyone had a similar problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南巷近海 2025-01-28 04:10:14

我忘记在API控制器上设置[授权]

    using Microsoft.AspNetCore.Authorization;

    [Authorize]
    [ApiController]
    public class TestController: ControllerBase

I forget to set [Authorize] on Api controller

    using Microsoft.AspNetCore.Authorization;

    [Authorize]
    [ApiController]
    public class TestController: ControllerBase
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文