最近,我遇到了这样一个问题 - 同名的两个属性(User)和返回类型,看似相同,都驻留在两个不同的命名空间中:
Microsoft.AspNetCore.Http.HttpContext.User
Microsoft.AspNetCore.Mvc.ControllerBase.User
VisualStudio给我的唯一描述是,其中一个与当前请求相关联,其次是当前操作。
在这段代码中,我正在尝试获取当前登录用户的名称。他们都给出了相同的结果。
var username = HttpContext.User.Identity.Name;
model.Username = username;
var username2 = User.Identity.Name;
model.Username2 = username2;
它们看起来非常相似。你能告诉我在哪些情况下我应该使用它们吗?
答案 0 :(得分:4)
根据ASP.NET Core source code,ControllerContext.User
属性只是HttpContext.User
属性的快捷方式:
/// <summary>
/// Gets the <see cref="ClaimsPrincipal"/> for user associated with the executing action.
/// </summary>
public ClaimsPrincipal User => HttpContext?.User;