Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.1 Use HttpContext in view

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: [email protected]

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.

like image 215
JianYA Avatar asked Oct 19 '25 08:10

JianYA


1 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
like image 116
Tetsuya Yamamoto Avatar answered Oct 22 '25 03:10

Tetsuya Yamamoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!