'Current User in .NET 5

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?



Solution 1:[1]

I forget to set [Authorize] on Api controller

    using Microsoft.AspNetCore.Authorization;

    [Authorize]
    [ApiController]
    public class TestController: ControllerBase

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mrKva