I'm building an ASP.NET Core Web API application and using the Microsoft.AspNetCore.Identity and Microsoft.AspNetCore.Authentication.JwtBearer libraries.
I'm signing in. Then I register the token in Swagger. Then I can access the UserName of the logged in user the following code. No problem No stress...
[Authorize]
[HttpGet("GetUserName")]
public ActionResult < string > GetMe()
{
// It's works and I can access the UserName of the logged in user
var userName = _userService.GetMyName();
return Ok(userName);
}
But I can't access the UserName the following code... I tried several things but failed. Both are inside a same Controller Class at the bottom of the page.
private string GetBuyerId()
{
// I need UserName here but I can't access the UserName of the logged in user
// returns null
var userNameTest1 = _userService.GetMyName();
// returns null
var userNameTest2 = GetMe();
// returns null
string userNameTest3 = _accessor.HttpContext.User.Identity.Name;
//returns null
var user = _userManager.GetUserName(HttpContext.User);
//AppUser applicationUser = await _userManager.GetUserAsync(User);
if (userNameTest1 == null)
return Request.Cookies["buyerId"];
else
return userNameTest1;
}