0

So far in Asp.Net I have used this command to get current username

var currentUsername = !string.IsNullOrEmpty(System.Web.HttpContext.Current?.User?.Identity?.Name)
 ? HttpContext.Current.User.Identity.Name
 : "Anonymous";

How should I use this method to get username in AspnetCore ?

Thank you

Orhun
1,2721 gold badge16 silver badges23 bronze badges
asked Jun 19, 2017 at 21:55
1
  • Within a controller or external to a controller? If external here is the IHttpContextAccessor that can be injected into dependent classes and access the HttpContext via that that interface. var context = accessor.HttpContext Commented Jun 19, 2017 at 22:34

1 Answer 1

1
 private readonly UserManager<User> _userManager ;
public LoginController(UserManager<User> userManager){
_userManager=userManager
}
public IActionResult GetUserName()
{
 User user = _userManager.GetUserAsync(HttpContext.User).Result;
 var userName=user.Username;
}
answered Jul 23, 2017 at 12:19
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.