4

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.

1
  • Is it should be @Context.User.Claims.Where(u => u.Type == "UserName").Select(c => c.Value).SingleOrDefault()? Commented Nov 15, 2018 at 3:37

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.