【问题标题】:ASP.NET Core HttpContext.User always emptyASP.NET Core HttpContext.User 始终为空
【发布时间】:2020-08-07 10:49:59
【问题描述】:

我在使用 asp.net core 3.1 时出现了奇怪的行为,如下当我调用时

这在 AccountController.Login 操作方法中调用 结果返回成功,用户将重定向到仪表板/索引操作方法,但是当我检查 HttpContext.User.Identity

它总是返回空标识对象,其所有内部属性都有默认值。

我尝试手动设置该值,但即使我将其设置为空,它仍然是空对象

这是我使用的完整 ConfigureService 方法

【问题讨论】:

  • ASP.NET Core 版本?
  • 我猜到了问题所在。能否请您添加Startup 类的ConfigureServices 方法的完整代码?
  • 确保按以下顺序调用中间件:UseRoutingUseAuthenticationUseAuthorizationUseEndpoints
  • 谢谢 Rena,这是我忘记添加“UseAuthentication”的问题,这是一种奇怪的行为,请将其添加为答案以检查是否正确

标签: asp.net-core .net-core


【解决方案1】:

您需要确保按以下顺序调用中间件:UseRoutingUseAuthenticationUseAuthorizationUseEndpoints

参考:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio#configure-identity-services

【讨论】: