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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With