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 ?
            Asked
            
        
        
            Active
            
        
            Viewed 1,055 times
        
    -1
            
            
        - 
                    Does this answer your question? [How to get current user in asp.net core](https://stackoverflow.com/questions/36641338/how-to-get-current-user-in-asp-net-core) – Pratap Alok Raj May 31 '21 at 14:24
- 
                    hi @AlokRaj . No I need to get user id in startup , not in controller – user3384879 May 31 '21 at 14:33
- 
                    Did you know that startup runs only ones. Doesn' t matter how many users. – Serge May 31 '21 at 17:22
1 Answers
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
