Hi @ANB ,
To access HttpContext or User in constructor, we should use IHttpContextAccessor, so, try to modify your code as below:
public class MyController : ControllerBase
{
private readonly string _userId;
private readonly string _username;
//required using Microsoft.AspNetCore.Http;
//required using System.Security.Claims;
private readonly IHttpContextAccessor _httpContextAccessor;
public MyController (IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_userId = httpContextAccessor.HttpContext.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
_username = httpContextAccessor.HttpContext.User?Identity?.Name;
}
[HttpGet]
public string GetUserId()
{
return _userId;
}
}
The result is below:
Note: If you meet the IHttpContextAccessor not register error, you can register IHttpContextAccessor in configure method:
Services.AddHttpContextAccessor();
Reference: Access HttpContext in ASP.NET Core
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion