最近,我遇到了这样一个问题——两个同名(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;
它们看起来非常相似。你能告诉我应该在什么情况下使用它们吗?
最佳答案
根据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;
关于c# - 登录用户声明的两种方式 - 哪种方式更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45676703/