.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

Table of Contents

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

47
Leave a Reply

avatar
5000
12 Comment threads
35 Thread replies
17 Followers
 
Most reacted comment
Hottest comment thread
17 Comment authors
Srikanth BollojulaAndriiMike BoutelleSam BLars Torbjörn Linden Recent comment authors
  Subscribe  
Notify of
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.

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!

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.