I can't access the UserName of the logged in user. (ASP.NET Core Web API)

Viewed 38

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.

https://github.com/enesozmus/Re-Store/blob/master/api/src/ReStore.API/Controllers/BasketController.cs

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;
}
1 Answers

Change like this

  [Authorize]
  private string GetBuyerId()

to

  //[Authorize]
  public string GetBuyerId()
Related