ASP.NET Core 2.1 Use HttpContext in view

Viewed 3032

I have this httpcontext claim that I would like to use in my view to show the current users username. This is how I do it so far:

<p>@Context.User.Claims.SingleOrDefault(u => u.Type == "UserName")</p>

However, the result is something like this:

UserName: user@email.com

Am I missing something? I tried to do this:

@Context.User.Claims.SingleOrDefault(u => u.Type == "UserName").Select(c => c.Value).SingleOrDefault()

But it doesn't allow me to use Select after the SingleOrDefault.

2 Answers

The SingleOrDefault() returns single element that matches with the criteria, not another IQueryable or IEnumerable collection which can be Select-ed later.

Returns a single, specific element of a sequence, or a default value if that element is not found.

You should use Where() to return a collection before using Select():

@Context.User.Claims.Where(u => u.Type == "UserName").Select(c => c.Value).SingleOrDefault()

For C# 6.0 and above, use null-conditional operator to get its value:

@Context.User.Claims.SingleOrDefault(u => u.Type == "UserName")?.Value

However, the result is something like this:

Because .SingleOrDefault returns a claim item, then the view renders the item with its .ToString method.

But it doesn't allow me to use Select after the SingleOrDefault.

.SingleOrDefault returns a item in the collection, while .Select expects a collection. You should just visit the .Value property of this item directly.

@Context.User.Claims.SingleOrDefault(u => u.Type == "UserName")?.Value
Related