c# - 登录用户声明的两种方式 - 哪种方式更好?

标签 c# asp.net-core

最近,我遇到了这样一个问题——两个同名(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/

相关文章:

c# - Azure 服务总线主题订阅的锁定持续时间重要性

c# - yield 返回与返回 IEnumerable<T>

c# - 如何在 .NET Core 中创建动画 gif

c# - 提高长时间操作的性能

C# - 如何获取当前用户图片

c# - 在 ASP.NET 中捕获由通用处理程序 (ashx) 文件引起的异常

c# - dotnet core 3.0在vs中打开解决方案时无法找到dotnetcore sdk

c# - 如何将 RoutePattern 添加到 Endpoint 对象

unit-testing - 替换 WebApplicationFactory 中的 DbContext 进行单元测试

c# - 如何将 Blazor 包含到现有项目中?