【问题标题】:I need to get the current user name in MVC 5我需要在 MVC 5 中获取当前用户名
【发布时间】:2018-11-16 14:33:19
【问题描述】:

我需要使用 HttpContext.Current.User.Identity.Name,但它总是返回为 null。我在项目属性中将匿名身份验证设置为禁用,并将 Windows 身份验证设置为启用。我的 web.config 中也有以下几行。

<authentication mode="Windows" />
<authorization>
  <deny users="?"/>
</authorization>

<providers>
....
  <add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>

我看过的每篇文章都建议执行我已经完成的步骤,但我仍然没有运气。

【问题讨论】:

  • 托管在 IIS 中还是签入 VS?
  • 只是在 localhost 上签入 VS
  • 另外,请确保您没有尝试在应用程序管道中过早访问 HttpContext 身份,例如在 Global.asax 的 Application_Start 方法中,因为身份在那里不可用。
  • 谢谢托马斯!你是对的,我一运行应用程序就得到了空错误。我将代码移到需要获取用户的位置,现在它可以正常工作。如果你回答我会标记它。

标签: asp.net-mvc


【解决方案1】:

用这个检查一下

string userName = System.Web.HttpContext.Current.User.Identity.Name

User.Identity.Name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多