.NET logo

How to get current user in ASP.NET Core?

This post was most recently updated on November 19th, 2019.

Reading Time: 2 minutes.

This post describes how to get the currently logged in user using ASP.NET Core. This is compared with how it’s done in .NET Framework.

Background

In .NET Core, a lot of things are done a bit differently. That’s what I’ve been learning building more and more stuff with it, instead of good old .NET Framework. The learning curve is definitely there, but it’s not that bad – most of the things work in a similar fashion, but a huge number of details are different.

In .NET Framework, you’d do this by accessing HttpContext.Current.User and its properties (see below for an example), in .NET Core this is handled via dependency injection.

var username = HttpContext.Current.User.Identity.Name;

You can’t do this in .NET Core. How to do it there, then?

Solution

This post describes how to manage user identity when programming your application – before that, you need to get your application registration done. To see what to do there, see my other post, here:

When that all is done, let’s jump into the ways you can access User/Identity in your program!

First, you add this in your Startup.cs, in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
 
     ...
 
     services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
 
}

Then you add these pieces of code to your Controller, database context or other class:

  1. Private variable to hold the injected reference to our HttpContextAccessor
  2. New variable with the correct type (or interface) to the class constructor (like IHttpContextAccessor httpContextAccessor below)
  3. Assignment from the injected variable (in the constructor) to the hidden private variable (to make the reference available outside the constructor)
private readonly IHttpContextAccessor _httpContextAccessor;
 
...
 
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
            : base(options)
{
  _httpContextAccessor = httpContextAccessor;
}

For our little example call further below, you’ll need to add a reference to Claims like this:

using System.Security.Claims;

And finally, you call it like this – for example, to get the reference to the user, and grab their id:

var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

And with this, you should be good! :)


(PS. If the embedded code blocks break again, sorry! Ping me in the comments below and I’ll fix them from the database. WordPress’ new editor, Gutenberg, doesn’t have a switch to disable autocompleting html, so it tries to “fix” what it thinks is html – but is actually a type definition in C# or similar. See more info here: https://github.com/WordPress/gutenberg/issues/14092 )

mm

41
Leave a Reply

avatar
5000
10 Comment threads
31 Thread replies
15 Followers
 
Most reacted comment
Hottest comment thread
14 Comment authors
Sam BLars Torbjörn LindenDeepthiThisIs TheListTian Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Alan
Guest
Alan

Hi Antti,

Thanks for taking the time to post, but this isn’t working for me at all. The ‘FindFirst’ method is returning NULL. When I inspect the _httpContextAccessor object, it doesn’t appear to have a user information either.

Do I need to run my app under IIS (full – not express) ? Do I need to try this with IE or Edge instead of Google Chrome?

I’m currently using ASP.net Core 2.2 with Visual Studio 2019 Community and Chrome.

Thanks,
Alan

Kanika
Guest
Kanika

Can you please elaborate this.. unable to catch you after second step!

Andrew Barzyk
Guest
Andrew Barzyk

Sorry, as many comments start… I’m new to EF… I added the code to my DB Context and am getting this error:
InvalidOperationException: The DbContext of type ‘AppDbContext’ cannot be pooled because it does not have a single public constructor accepting a single parameter of type DbContextOptions.

Any chance you could explain in more detail how you “add this to your Controller, database context or other class?”

Amit Sadashiv Patil
Guest
Amit Sadashiv Patil

When I am doing the above procedure in one of my controller class, it works. I am able to see the username. But when I do this procedure in my ApplicationDbContext (InterviewSchedulerContext class in my case) class, the above-mentioned solution does not work. I am getting “Microsoft.AspNetCore.Http.IHttpContextAccessor.HttpContext.get returned null” error.

Error details:
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=InterviewScheduler
StackTrace:
at InterviewScheduler.Entities.InterviewSchedulerContext..ctor(DbContextOptions`1 options, IHttpContextAccessor httpContextAccessor) in C:\Users\amipatil\source\repos\InterviewScheduler 1857 83326\InterviewScheduler\Entities\InterviewSchedulerContext.cs:line 22

Could you help me out?
Thank you in advance.

John Hermsen
Guest
John Hermsen

Hi Amit,

EFCore uses an InternalServiceProvider which is different from the ApplicationServiceProvider.
To access the application service provider you can use the IDbContextOptions service.
E.g. constructor:
public MyContext(IDbContextOptions dbContextOptions)
{
var coreOptionsExtension = _dbContextOptions?.FindExtension();
var context Accessor = coreOptionsExtensions.ApplicationServiceProvider.GetService();
}

Hope this helps.

Ivan Salo
Guest
Ivan Salo

Hi Antti,

I am getting an error in EF Core 2.2
The DbContext of type ‘DataContext’ cannot be pooled because it does not have a single public constructor accepting a single parameter of type DbContextOptions.

Can you suggest how to resolve it?

Thanks,
Ivan Salo.

kintela
Guest
kintela

Hi Antti,
I’m trying this in my webAPI project hosted in web site in IIS with Windows Authentication enabled
I have this in my controller
[Route(“empleados”)]
public class EmployeeController : Controller
{
private readonly IMediator mediator;
private readonly IHttpContextAccessor httpContextAccesor;

public EmployeeController(IMediator mediator, IHttpContextAccessor httpContextAccesor)
{
this.mediator = mediator;
this.httpContextAccesor = httpContextAccesor;
}

[HttpGet]
[Route(“”)]
public IActionResult Get()
{
var userId = this.httpContextAccesor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return Ok(userId);
}
But when I make the call I get the pop up to start session and then HTTP ERROR 500

Any idea, please?

Thanks

Tian
Guest
Tian

Thanks for post, but when I call var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; it return name of user. How can I found userId.
Thanks

Lars Torbjörn Linden
Guest
Lars Torbjörn Linden

UserName = claimsPrincipal.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value,
Roles = claimsPrincipal.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray(),
Email = claimsPrincipal.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Upn)?.Value,
FirstName = claimsPrincipal.Claims.SingleOrDefault(c => c.Type == ClaimTypes.GivenName)?.Value,
LastName = claimsPrincipal.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Surname)?.Value

ThisIs TheList
Guest
ThisIs TheList

Just wanted to say that on an ASP NET CORE 3.1 + Identity4 + Login project, I was able to follow the directions you provided in this article and successfully retrieve the current user information from within a method in a Web API Controller. That was something I was struggling with after moving from a CORE 2 + older Identity project to the latest/greatest. Thanks for the clear explanation.

Deepthi
Guest
Deepthi

Hi,
I have a .net core 2.2 web application where the Signin happens using the following code

await _httpContextAccessor.HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
The values of httpContextAccessor.httpContext.user.identity.name are retained properly for further requests and works in VS2017 in devlopment environment.

But on deploying to server with IIS the same code doesn’t work and the values for httpContextAccessor.User.Identity.Name is returning empty.

Any idea what the problem is? Any help will be greatly appreciated.

Thanks

Sam B
Guest
Sam B

Hello,

Thanks so much for the guide. Im currently using Dapper as my ORM to make data calls for my identity user. I referenced- https://markjohnson.io/articles/asp-net-core-identity-without-entity-framework/ and am wondering how to set up the httpcontextaccessor without a dbcontext class. Any insight is helpful :)

Thanks,
SB