C
C#2y ago
aaarianme

❔ .Net Core API User.FindFirstValue(ClaimTypes.NameIdentifier) in every action?!

Hi everyone I have the end point below
[HttpPost, Route("stores/new"), Authorize(policy: "client")]
public async Task<IActionResult> AddNewStore(NewStoreRequestDto store)
{
int userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
//do something
}
[HttpPost, Route("stores/new"), Authorize(policy: "client")]
public async Task<IActionResult> AddNewStore(NewStoreRequestDto store)
{
int userId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
//do something
}
now the line where i get the userId is being repeated in every action where i need the userId. is there a better way to have this value saved globally or in the controller scope or something?
6 Replies
Angius
Angius2y ago
I just created an extension method so I can do var uid = User.GetNumericId() and done
aaarianme
aaarianme2y ago
thats smart
Angius
Angius2y ago
But you could probably create your own controller class that inherits Controller or ControllerBase or whatever you need, and adds user ID as a property or a field Then have all your controllers inherit that
aaarianme
aaarianme2y ago
i think ill do that as well i tried doing that but it didnt work what does ur extension method return if userId not found null?
Angius
Angius2y ago
public static class ClaimsPrincipalEx
{
public static long? GetNumericId(this ClaimsPrincipal principal)
{
var user = principal.FindFirstValue(ClaimTypes.NameIdentifier);
var castResult = long.TryParse(user, out var userId);
return castResult ? userId : null;
}

public static string? GetUsername(this ClaimsPrincipal principal)
=> principal.FindFirstValue(ClaimTypes.Name);
}
public static class ClaimsPrincipalEx
{
public static long? GetNumericId(this ClaimsPrincipal principal)
{
var user = principal.FindFirstValue(ClaimTypes.NameIdentifier);
var castResult = long.TryParse(user, out var userId);
return castResult ? userId : null;
}

public static string? GetUsername(this ClaimsPrincipal principal)
=> principal.FindFirstValue(ClaimTypes.Name);
}
It's nullable So I can easily do
if (User.GetNumericId() is not {} uid) return NotFound();
// use `uid`
if (User.GetNumericId() is not {} uid) return NotFound();
// use `uid`
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.