GrayCat
GrayCat

Reputation: 1797

Two ways of getting logged in user claims - which is better?

Recently, I've encountered such a problem - two properties of the same name (User) and return type, seemingly doing the same, reside in two different namespaces :

Microsoft.AspNetCore.Http.HttpContext.User

Microsoft.AspNetCore.Mvc.ControllerBase.User

The only description VisualStudio gives me says that one of them is associated with current request, second - with current action.

In this bit of code I'm trying to get name of currently logged user. They both give the same result.

var username = HttpContext.User.Identity.Name;
model.Username = username;
var username2 = User.Identity.Name;
model.Username2 = username2;

They seem very similar. Can you tell me in what cases should I use each of them?

Upvotes: 1

Views: 271

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32058

According to the ASP.NET Core source code, the ControllerContext.User property is just a shortcut to the HttpContext.User property:

/// <summary>
/// Gets the <see cref="ClaimsPrincipal"/> for user associated with the executing action.
/// </summary>
public ClaimsPrincipal User => HttpContext?.User;

Upvotes: 4

Related Questions