Getting The UserID Using ASP.Net Identity

I’ve started working on a project that uses the new ASP.Net Identity library with MVC5. The first thing I struggled with is getting the user’s ID. It’s actually quite simple but I had a hard time finding a straightforward answer so I’m writing it up here in case it helps.

First, add this using statement:

using Microsoft.AspNet.Identity;

Once you’ve added this using statement there is a new method available on the regular User.Identity property:

var userId = User.Identity.GetUserId();

That’s it! The GetUserId extension method will return the user’s id, which is a string this time around.