-1

How I can get current user id in Configure Services method. I need to send user Id when inject some service. or it is not possible ?

1 Answers1

1

I need to send user Id when inject some service. or it is not possible ?

HttpContext is only valid during a request. The ConfigureServices method in Startup is not a web call and, as such, does not have a HttpContext. So the User information also cannot be got. You need register the IHttpContextAccessor and DI it by constructor in your services. Then you could get HttpContext.User infomation successfully.

Register the IHttpContextAccessor:

services.AddScoped<IHttpContextAccessor,HttpContextAccessor>();

DI in the service:

public interface IService
{
    string GetUserId();
}

public class Service : IService
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public Service(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    public string GetUserId()
    {
        var id = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
        return id;
    }
}

Register the service:

services.AddScoped<IHttpContextAccessor,HttpContextAccessor>();
services.AddScoped<IService, Service>(); //add this...

More explanations you could refer to here.

Rena
  • 30,832
  • 6
  • 37
  • 72