Hi @Cenk ,
To access the HttpContext.User's claims from the service, you can try to use AddHttpContextAccessor
service and IHttpContextAccessor
.
In your application, register the AddHttpContextAccessor
services in the Program.cs
or Startup.cs
file:
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<IPalasServices, PalasServices>();
Then in the PalasServices service, refer to the following code to inject the IHttpContextAccessor, and then get the user claims:
public class PalasServices : IPalasServices
{
private readonly IHttpContextAccessor _http;
public PalasServices(IHttpContextAccessor http)
{
_http = http;
}
public string GetCurrentUser()
{
return _http.HttpContext.User.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
}
}
The output as below:
More detail information, see 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