【问题标题】:Getting Current User Id in AspNet Core在 AspNet Core 中获取当前用户 ID
【发布时间】:2017-11-22 06:17:17
【问题描述】:

到目前为止,在 Asp.Net 中我使用此命令获取当前用户名

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

我应该如何使用这种方法在 AspnetCore 中获取用户名?

谢谢

【问题讨论】:

  • 控制器内部还是控制器外部?如果这里是外部IHttpContextAccessor,则可以将其注入依赖类并通过该接口访问HttpContextvar context = accessor.HttpContext

标签: asp.net-mvc asp.net-web-api asp.net-core asp.net-identity


【解决方案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;


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 2018-10-16
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多