How To Get UserId() Method From ASP.NET Identity Directly in Razor

If somebody is looking for an ASP.NET Core solution (as I was an hour ago), there is a solution for you:

@using Microsoft.AspNetCore.Identity

var user = await UserManager.GetUserAsync(User);
var userId = user?.Id;

Just wanted to add my take as both of the above responses didn't work for me.

@using Microsoft.AspNetCore.Identity

@inject UserManager<IdentityUser> userManager

@if (project.CreatorId == userManager.GetUserId(User))
{
  //do something
}

I added

@using Microsoft.AspNetCore.Identity
@inject UserManager<IdentityUser> userManager 

to _ViewImports.cshtml because I need to use it in several views.


This answer and question are for ASP.NET MVC 5,not ASP.NET CORE

Add the following using statement at the top of your view file.

using Microsoft.AspNet.Identity;

Following this, you should be able to use User.Identity.GetUserId()