.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
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