.NET logo

How to get current user in ASP.NET Core?

This post was most recently updated on April 4th, 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

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

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

Then you add this to your Controller, database context or other class:

private readonly IHttpContextAccessor _httpContextAccessor;
 
...
 
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
            : base(options)
{
  _httpContextAccessor = httpContextAccessor;
}

And finally, you call it like this:

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

You’ll need to add a reference to Claims like this:

using System.Security.Claims;

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 )

Antti K. Koskela

Antti Koskela is a proud digital native nomadic millenial full stack developer (is that enough funny buzzwords? That's definitely enough funny buzzwords!), who works as a Solutions Architect for Valo Intranet, the product that will make you fall in love with your intranet. Working with the global partner network, he's responsible for the success of Valo deployments happening all around the world.

He's been a developer from 2004 (starting with PHP and Java), and he's been bending and twisting SharePoint into different shapes since MOSS. Nowadays he's not only working on SharePoint, but also on .NET projects, Azure, Office 365 and a lot of other stuff.

This is his personal professional (e.g. professional, but definitely personal) blog.

Leave a Reply

avatar
5000
  Subscribe  
Notify of